Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date is not properly calculated in Java. Issue with zone

Tags:

java

datetime

I have a date format stored in DB, for example:

Thu Aug 27 2020 00:00:00 GMT-0400 (Eastern Daylight Time)

I want to display the same date as output. Seems like I am missing something zone. It's evolving to be one day prior to this date.

I did the following:

DateTimeFormatter etFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mma 'ET'");
ZoneId zoneId = ZoneId.of("America/New_York");
ZonedDateTime zonedDateTime = ((Timestamp) date).toLocalDateTime().atZone(zoneId);
etFormat.format(zonedDateTime)

Output:

08/26/2020 at 08:00PM ET

What am I doing wrong?

like image 919
Nilotpal Avatar asked Jun 06 '26 15:06

Nilotpal


1 Answers

In your database you have the date time with offset UTC-04:40 (which is 4 hr behind from UTC assuming America/New_York timezone). And when it converts into Timestamp it will be stores in UTC without offset which is 08/26/2020 at 08:00PM.

So first convert the Timestamp into Instant of UTC and then convert the Instant into ZonedDateTime with the zone information

 ZonedDateTime dateTime = timestamp.toInstant()
                           .atZone(ZoneOffset.UTC)
                           .withZoneSameInstant(ZoneId.of("America/New_York"));
 etFormat.format(dateTime);     //08/27/2020 at 00:00PM ET
like image 89
Deadpool Avatar answered Jun 09 '26 06:06

Deadpool