Skip to content
Advertisement

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement