javadatejava-timedatetime-parsingoffsetdatetime

Why can't OffsetDateTime parse '2016-08-24T18:38:05.507+0000' in Java 8


The expression

OffsetDateTime.parse("2016-08-24T18:38:05.507+0000")

results in the following error:

java.time.format.DateTimeParseException: Text '2016-08-24T18:38:05.507+0000' could not be parsed at index 23

On the other hand,

OffsetDateTime.parse("2016-08-24T18:38:05.507+00:00")

works as expected.

DateTimeFormatter's doc page mentions zone offsets without colons as examples. What am I doing wrong? I'd rather not mangle my date string to appease Java.


Solution

  • You are calling the following method.

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

    It uses uses DateTimeFormatter.ISO_OFFSET_DATE_TIME as DateTimeFormatter which, as stated in the javadoc, does the following:

    The ISO date-time formatter that formats or parses a date-time with an offset, such as '2011-12-03T10:15:30+01:00'.

    If you want to parse a date with a different format as in 2016-08-24T18:38:05.507+0000 you should use OffsetDateTime#parse(CharSequence, DateTimeFormatter). The following code should solve your problem:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    OffsetDateTime.parse("2016-08-24T18:38:05.507+0000", formatter);