Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading