5

I am trying parse ZonedDateTimes from Strings in the following format:

2017-08-10 16:48:37 -0500

I had previously done so successfully using Jodatime's DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss Z").

I am trying to replace Jodatime with the Java Time API, and the same pattern no longer works.

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss Z");
ZonedDateTime.parse("2017-08-10 16:48:37 -0500", dtf);

results in the following exception:

java.time.format.DateTimeParseException: Text '2017-08-10 16:48:37 -0500' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {DayOfMonth=10, OffsetSeconds=-18000, WeekBasedYear[WeekFields[SUNDAY,1]]=2017, MonthOfYear=8},ISO resolved to 16:48:37 of type java.time.format.Parsed

What is the proper pattern to use for the format string in the Java Time API?

kes
  • 5,513
  • 8
  • 39
  • 69

1 Answers1

6

You should replace your YYYY part with uuuu

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss Z");
    ZonedDateTime parsed = ZonedDateTime.parse("2017-08-10 16:48:37 -0500", dtf);
Aleh Maksimovich
  • 2,336
  • 5
  • 18
  • 2
    Interesting, what exactly is the difference between `year` (YYYY) and `year-of-era` (uuuu)? – a_horse_with_no_name Nov 02 '17 at 20:43
  • I can't explain it good myself. But pay attention that: * u year * y year-of-era * Y week-based-year https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html – Aleh Maksimovich Nov 02 '17 at 20:47
  • 2
    **y** = year, **Y** = week year. If one uses a **week number** (1-53) the first half week of this year 2017 could be 52 whereas its **week year** would have been yesteryear 2016. – Joop Eggen Nov 02 '17 at 20:51
  • 1
    The [accepted answer here](https://stackoverflow.com/questions/41177442/uuuu-versus-yyyy-in-datetimeformatter-formatting-pattern-codes-in-java) explains it quite well. It's a breaking of established pattern to say the least. – alainlompo Nov 02 '17 at 20:53
  • And JodaTime indeed has its own pattern syntax, you cannot simply overtake Joda-patterns to the world of `java.time`-package (or even to old `SimpleDateFormat`-patterns). All three types of pattern definitions are different. – Meno Hochschild Nov 03 '17 at 14:37