3

I'm trying to convert the string Wed July 2019 10:53 PM to LocalDateTime object using the following code:

String dateAndTimeAsStr = "Wed July 2019 10:53 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMMM yyyy h:mm a");
LocalDateTime dateAndTimeAsLocalDateTime = LocalDateTime.parse(dateAndTimeAsStr, formatter);

Yet when I run this code I get the following error:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'Wed July 2019 10:53 PM' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {DayOfWeek=3, MonthOfYear=7, Year=2019},ISO resolved to 22:53 of type java.time.format.Parsed

Changing yyyy to YYYY and h to hh did not yield any different results.

According to this answer on SO and the documentation it seems my pattern matches the text supplied.

What am I doing wrong?

Thanks

S.O.S
  • 848
  • 10
  • 30

1 Answers1

6

Missing day-of-month

Your input string lacks the day of month. It says "July 2019" but not what day within July.

The formatted date string is irreversible (as in you can format existing LocalDateTime using the formatter, but cannot parse it back). as it's missing the day value.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
akk202
  • 194
  • 1
  • 10
  • I tried it on my end and it worked for me. Or you can use the "Date" object as suggested in answer below which is more forgiving. – akk202 Jul 11 '19 at 17:28