简体   繁体   中英

Pattern “YYYY-MM-dd HH:mm:ss Z” causes parsing exception where Jodatime did not

I am trying parse ZonedDateTime s 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM