lapots
lapots

Reputation: 13415

OffsetDateTime parse different behavior in Java 8 and Java 11

When I execute this in Java 8

String fromDate = "2007-12-03T10:15:30+01";
OffsetDateTime from = OffsetDateTime.parse(fromDate);

I receive the error

Exception in thread "main" java.time.format.DateTimeParseException: Text '2007-12-03T10:15:30+01' 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.OffsetDateTime.parse(OffsetDateTime.java:402)
    at java.time.OffsetDateTime.parse(OffsetDateTime.java:387)
    at MyClass.main(MyClass.java:6)

But when doing the same in Java 11 it passes just fine. What has changed? In Javadoc I don't see any changes.

Upvotes: 1

Views: 1650

Answers (2)

Lesiak
Lesiak

Reputation: 26094

Both Java 8 and Java 11 use ISO_OFFSET_DATE_TIME as a default DateTimeFormatter:

public static OffsetDateTime parse(CharSequence text) {
    return parse(text, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}

The implementation of ISO_OFFSET_DATE_TIME has changed, which is documented in the javadoc

Java 11 ISO_OFFSET_DATE_TIME

The offset ID. If the offset has seconds then they will be handled even though this is not part of the ISO-8601 standard. The offset parsing is lenient, which allows the minutes and seconds to be optional. Parsing is case insensitive.

Java 8 ISO_OFFSET_DATE_TIME

The offset ID. If the offset has seconds then they will be handled even though this is not part of the ISO-8601 standard. Parsing is case insensitive.

Upvotes: 3

Bedla
Bedla

Reputation: 4939

This is bug JDK-8032051 fixed in JDK9. In JDK8 is not java.time.format.DateTimeFormatter fully ISO-8601 compliant, because does not support lenient timezone format like +01. You can try with TZ +01:00, it will be parsed successfully.

Because this bug also affects ZonedDateTime (fix have been applied in DateTimeFormatter), you can look at java.time.ZonedDateTime.parse and iso8601? for possible solutions.

Upvotes: 0

Related Questions