Why Instant.parse() string with timezone behaviour in java8 is different than java 17

Advertisements

The following code snippet

Instant.parse("2023-08-08T00:00:00+02:00")

compiles and executes as expected in java-17. But when executed with java-8, throws the following exception

java.time.format.DateTimeParseException: Text '2023-08-01T00:00:00+02:00' could not be parsed at index 19

    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.Instant.parse(Instant.java:395)
    ...

My question is why? Did something change in java.time api?

Please note, i do know a way to workaround this, the following code works in java-8

OffsetDateTime.parse("2023-08-01T00:00:00+02:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME).toInstant()

It produces the desired result. I am interested to know whether within java-time api implementation, behaviour has been changed?

>Solution :

This change occurred in Java 12. Versions 8 to 11 will throw this exception, while versions from 12 onwards will accept a time zone offset.

As the documentation says, the Instant.parse method uses the DateTimeFormatter.ISO_INSTANT parser. The latter has been changed between versions 11 and 12 (see links). In version 12, the following sentence was added to the description of the ISO_INSTANT parser:

When parsing, the behaviour of DateTimeFormatterBuilder.appendOffsetId() will be used to parse the offset, converting the instant to UTC as necessary.

Leave a ReplyCancel reply