Bax
Bax

Reputation: 4476

Java 8 DateTimeFormatter can't parse a date formatted by itself

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss z");
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
// 2016-10-10 09:28:45 PDT
String s = zonedDateTime.format(formatter);
// this call fails
ZonedDateTime.parse(s, formatter);

What's wrong with the given snippet, shouldn't formatter.parse(date.format(formatter)) evaluate to the same date ?
Exception :

java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {MilliOfSecond=0, MicroOfSecond=0, HourOfAmPm=9, MinuteOfHour=28, NanoOfSecond=0, SecondOfMinute=45},ISO,America/Los_Angeles resolved to 2016-10-10 of type java.time.format.Parsed

Upvotes: 3

Views: 1151

Answers (2)

clay
clay

Reputation: 20390

java.time.ZonedDateTime.parse("2016-10-10T09:28:45-07:00");

java.time.LocalDate.parse("2016-10-10");

Upvotes: 0

greg-449
greg-449

Reputation: 111142

Since you have specified hh (lower case h) for the 12 hour clock you have lost the information about whether this is AM / PM so the parse is complaining about that.

Using yyyy-MM-dd hh:mm:ss a Z to include the AM/PM indicator works.

Upvotes: 5

Related Questions