Instant.toEpochMilli mismatch b/w Java 8 & 11?

However, when running the code above on Java 11, the output is an epoch value for UTC/GMT timezone instead.

Debugging the code reveals that the library is not correctly setting the offset.

Can someone please provide assistance on how to get the correct epoch value for New York on Java 11?

String strDate = "2022-07-18 17:52:23 America/New_York";
DateTimeFormatter frmt  = new DateTimeFormatterBuilder()
    .appendPattern("yyyy-MM-dd HH:mm:ss VV")
    .parseDefaulting(ChronoField.HOUR_OF_DAY,0)
    .parseDefaulting(ChronoField.MINUTE_OF_HOUR,0)
    .parseDefaulting(ChronoField.SECOND_OF_MINUTE,0)
    .parseDefaulting(ChronoField.NANO_OF_SECOND,0)
    .parseDefaulting(ChronoField.OFFSET_SECONDS,0)
    .toFormatter();

TemporalAccessor temporal = frmt.parse(strDate);
System.out.println(Instant.from(temporal).toEpochMilli()); 

When running the code above on Java 11, the output is an epoch value for UTC/GMT timezone instead of the expected epoch value for New York. Debugging the code reveals that the library is not correctly setting the offset.

Can someone please provide assistance on how to get the correct epoch value for New York on Java 11?

To get the correct epoch value for New York on Java 11, you need to set the correct time zone offset in the code. Here’s the modified code:

String strDate = "2022-07-18 17:52:23 America/New_York";
DateTimeFormatter frmt = new DateTimeFormatterBuilder()
    .appendPattern("yyyy-MM-dd HH:mm:ss VV")
    .toFormatter()
    .withZone(ZoneId.of("America/New_York"));

ZonedDateTime zonedDateTime = ZonedDateTime.parse(strDate, frmt);
System.out.println(zonedDateTime.toInstant().toEpochMilli());

This code sets the time zone to “America/New_York” using the withZone() method. Then, it parses the input string into a ZonedDateTime object and retrieves the epoch millisecond value using the toInstant().toEpochMilli() method. The output will be the correct epoch value for New York.