3

This is my first post, so if I am not following all the rules and conventions please forgive me. I have this problem with this code, which gives different epoch time millis in java 8 and 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()); 

Output:

  • Java 8 - 1658181143000 the right value for New York
  • Java 11 - 1658166743000 wrong. This value is for UTC/GMT

It produces the correct result 1658181143000 in java8, which is epoch value for New_York timezone. But it gives 1658166743000 in java11 which is epoch representation of UTC timezone. Debugging through the code, I figured that the library is not setting the offset at the right place in the code. Any help is greatly appreciated.

Thanks in advance

Was expecting the right epoch value for New York.

k314159
  • 5,051
  • 10
  • 32
  • I think you may need to pass the timezone/locale as a JDK argument in Java 11. Could be related: [Joda Date Time returns very different results between Java 8 vs Java 11](https://stackoverflow.com/questions/61199566/joda-date-time-returns-very-different-results-between-java-8-vs-java-11) – Mr. Polywhirl Jun 23 '23 at 15:09
  • Don't start a question title with "Question about"... summarize your actual question. Also don't add fluff like how your new and don't add thanks. – Mark Rotteveel Jun 23 '23 at 16:13

1 Answers1

3

I don't know if this is a "misfeature", but it seems that the problem is caused by this:

.parseDefaulting(ChronoField.OFFSET_SECONDS,0)

If you leave this line out, then your code will work. You may have assumed that parseDefaulting(ChronoField.OFFSET_SECONDS,0) makes your ZoneId optional. In fact, it doesn't. It only defaults the offset, which are specified by O, X, x or Z. The VV specifies zone id, which is differeent from offset. So what you've done is parsed a string which contains zone id, but doesn't contain offset, so it defaults to 0.

k314159
  • 5,051
  • 10
  • 32
  • Thank you for the prompt reply. That is working in this scenario, but there are other dateFormats that were working in java8, but not working in Java11. Looks like the backward compatibility of the java.time package iin java11 is broken either intentionally or accidentally. – Mathew Mani Jul 02 '23 at 00:44