3

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?

Solci
  • 296
  • 4
  • 14
  • 1
    You might want to mention that parsing using **"week-based-year"** is not working... You might get faster answers that way... – Codebender Aug 31 '15 at 14:07
  • Try this: http://stackoverflow.com/questions/23596530/unable-to-obtain-zoneddatetime-from-temporalaccessor-using-datetimeformatter-and – Zarwan Aug 31 '15 at 14:39

1 Answers1

2

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

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
  • Many thanks. I spent a lot of time searching for weird solutions that i didn't noticed the capital Y – Solci Aug 31 '15 at 15:54
  • @Solci The way to detect this kind of mistake is to test a snippet of working code. Then compare to your own until you see your mistake. Hundreds of such samples posted here on StackOverflow. – Basil Bourque Aug 31 '15 at 19:10