Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

date - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...