Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse string with offset to Instant Java 11

I am trying to parse the following string 2021-10-15T08:39:05+02:00 into an Instant this works seamlessly using Java 15 but throws an error for Java 11.

java.time.format.DateTimeParseException: Text '2021-10-19T11:06:35+02:00' could not be parsed at index 19

Why is that the case?

Instant.parse("2021-10-15T08:39:05+02:00");

Edit: Java 15

enter image description here

like image 519
joachim Avatar asked May 26 '26 14:05

joachim


1 Answers

Instant.parse says:

The string ... is parsed using DateTimeFormatter.ISO_INSTANT.

So, read the docs for DateTimeFormatter.ISO_INSTANT:

  • Java 15

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

  • Java 11

    When parsing ... (nothing about how the offset is parsed)

The behavior has changed between the two to make DateTimeFormatter.ISO_INSTANT (and code making using of it) accept a broader range of inputs.

To get an Instant from that string with Java 11, you can first parse to a OffsetDateTime, then use toInstant() to get the corresponding Instant.

like image 59
Andy Turner Avatar answered May 28 '26 03:05

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!