3

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

0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

This is due to the fact that java.time.format.DateTimeFormatter.html#ISO_INSTANT, used internally by the java.time.Instant#parse, behavior have changed to support the timezone offset when parsing an instant.

You can achieve the same behavior that will work seamlessly across different Java versions starting from 1.8 onward using the java.time.OffsetDateTime#parse chained with java.time.OffsetDateTime#toInstant:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.