#Date offset by 2 hours

14 messages · Page 1 of 1 (latest)

tepid cedar
#

Hello, i need some help with Date class. It comes from an old project that has to be upgraded to springboot for the REST controller part WITHOUT CHANGING ANY OTHER CODE. So every "Date" has to stay as Date, sadly.

I found a problem when i retrieve the date from DB it has -2hours diff. So i made a controller to test it:

@GetMapping("testing")
public Date testDate(@RequestParam @DateTimeFormat(pattern="yyyy-MM-dd")Date date){
    return date;
}

i pass "2023-06-27" and i receive "2023-06-26T22:00:00.000+00:00"

How can i solve this? Remember, can't change any single Date to LocalDate or whatever

valid spindleBOT
#

This post has been reserved for your question.

Hey @tepid cedar! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

icy quest
#

the time isn't offset, it's perceiving a timezone (yours most likely)
DateTimeFormat seems to assume timezones

#

2023-06-27 is converted to 2023-06-27T00:00:00.000+02:00, which is equivalent to 2023-06-26T22:00:00.000+00:00

icy quest
#

seems like a bunch of Date apis are deprecated in favor of Calendar apis, but seems like you can convert between the two

#

Date to Calendar: new Calendar().setTime(date)
Calendar to Date: calendar.getTime()
you could then normalize the timezone offset via Calendar's methods

#

to get the offset seems to be -(calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)) / (60 * 1000)
you could add that to the result of calendar.getTimeInMillis() then make that a Date via new Date(timestamp)
looks like you could alternatively use calendar.add(Calendar.HOUR_OF_DAY, offset) but idk if that'll work properly

#

try exploring your avenues

dusty loom
#

DateFormat can be simply set a timezone. It's by far the easiest way to deal

#

I am not sure what to do to control how Spring will deserialize a string parameter into a Date object, but receiving this parameter as the literal String it was given, makes it easy to then do whatever you want with it with DateFormats

sudden timber