6

When running the below code I get different behaviour with different versions of the JDK:

In Java 8 I get:

2020-01-07T09:34:38.994Z

In Java 11 I get:

2020-01-07T09:37:05.55126Z
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class MyClass {
    public static void main(String args[]) {
        ZonedDateTime now = ZonedDateTime.now();

        DateTimeFormatter isoOffsetDateTime = DateTimeFormatter.ISO_OFFSET_DATE_TIME;

        String format = isoOffsetDateTime.format(now);

        System.out.println(format);
    }
}

Running in https://www.jdoodle.com/online-java-compiler/ just to make it easier to swap JDKs quickly

Is this change documented anywhere as I couldn't find anything and/or does anyone know why it's happening ? I spotted this as the DateTimeFormatter.ISO_OFFSET_DATE_TIME is the default Jackson formatter for a ZonedDateTime.

Amongalen
  • 3,101
  • 14
  • 20
Arcjc
  • 63
  • 3
  • Does this answer your question? [ZonedDateTime change behavior jdk 8/11](https://stackoverflow.com/questions/56255020/zoneddatetime-change-behavior-jdk-8-11) – amer Jan 07 '20 at 10:21
  • @amer that seems to be a different problem (time zone related, while this is related to the precision of the fractional seconds) – Mark Rotteveel Jan 08 '20 at 10:33
  • @MarkRotteveel Ok, my bad – amer Jan 08 '20 at 10:34

2 Answers2

10

The behaviour of the formatter hasn't changed, but the thing you're formatting has.

The precision of datetimes returned by now() methods increased. JDK-8068730

Michael
  • 41,989
  • 11
  • 82
  • 128
0

If you want to return the old milliseconds format with Java 9+, you can truncate using temporal ChronoUnit for Instant or ZonedDateTime. Example:

import java.time.temporal.ChronoUnit;

ZonedDateTime.now().truncatedTo(ChronoUnit.MILLIS).toString();
// OR
Instant.now().truncatedTo(ChronoUnit.MILLIS).toString();

NOTE: In a very rare case, when now() executes at 000 milli-seconds of time, you will see above returns without SSS in the output i.e 2020-01-07T09:34:38Z instead of 2020-01-07T09:34:38.000Z.

Imran
  • 5,542
  • 3
  • 23
  • 46