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
631 views
in Technique[技术] by (71.8m points)

date - Cant parse recently formatted ZonedDateTime Java 8

Why this code

DateTimeFormatter SENT_DATE_FORMATTER = DateTimeFormatter.ofPattern("E, d MMM YYYY HH:mm:ss Z", Locale.US);
ZonedDateTime now = ZonedDateTime.now();
String dateStr = now.format(SENT_DATE_FORMATTER);
System.out.println(dateStr);

ZonedDateTime zoned = ZonedDateTime.parse(dateStr, SENT_DATE_FORMATTER);

Prints the correct date on the sysout line but throws a DateTimeParseException (Unable to obtain ZonedDateTime from TemporalAccessor) on the parse line?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Capitalized Y stands for week-based-year, see javadoc. In order to make the parser working you rather need to change it to year (u) or year-of-era (y). Then the parser can create a date out of calendar year, month (M) and day-of-month (d). Keep in mind that the week-based-year can relate to previous or next calendar year, not the actual one if your month and day-of-month are near the start or end of calendar year. Therefore it is not possible to just equalize the week-based-year to the calendar year! And without a precisely defined calendar year it is not possible to form a date.

Otherwise, if you had the week-of-week-based-year (w) in your pattern, too, then your parser would be able to understand the input because week-based-year (Y), week-of-week-based-year (w) and day-of-week (E) would also make an interpretable combination for a date.

Note however, that all given details in the input matching your pattern must be consistent (for example 2015-08-31 is Monday and not Tuesday) otherwise the parser will complain again (at least in strict mode).


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

...