1

I'm trying to convert the String Fri August 16 2019 12:08:55 AM to LocalDateTime object using the following code:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMMM d YYYY h:mm:ss a", Locale.US);
String timestamp = "Fri August 16 2019 12:08:55 AM";
localDateTime = LocalDateTime.parse(timestamp, formatter);

This code throws following exception:

java.time.format.DateTimeParseException: Text 'Fri August 16 2019 12:08:55 AM' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {WeekBasedYear[WeekFields[SUNDAY,1]]=2019, MonthOfYear=8, DayOfWeek=5, DayOfMonth=16},ISO resolved to 00:08:55 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(Unknown Source)
    at java.time.format.DateTimeFormatter.parse(Unknown Source)
    at java.time.LocalDateTime.parse(Unknown Source)
    at suppliers.pojos.PriceFluctuationPOJO.<init>(PriceFluctuationPOJO.java:51)
    at suppliers.pojos.PriceFluctuationPOJO.readFromPriceFluctuationCSVFile(PriceFluctuationPOJO.java:163)
    at amzn.Main.main(Main.java:60)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {WeekBasedYear[WeekFields[SUNDAY,1]]=2019, MonthOfYear=8, DayOfWeek=5, DayOfMonth=16},ISO resolved to 00:08:55 of type java.time.format.Parsed
    at java.time.LocalDateTime.from(Unknown Source)
    at java.time.format.Parsed.query(Unknown Source)

Based on this and this thread on SO it seems the format is correct.

What's causing the exception?

Thanks

S.O.S
  • 848
  • 10
  • 30

1 Answers1

2

You should not have single quotes in your input String, and your pattern is off. You wanted yyyy (not YYYY). Like,

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
        "EEE MMMM d yyyy hh:mm:ss a", Locale.US);
String timestamp = "Fri August 16 2019 12:08:55 AM";
LocalDateTime localDateTime = LocalDateTime.parse(timestamp, formatter);
System.out.println(localDateTime);

Outputs (here)

2019-08-16T00:08:55
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Oops! I mistakenly copied the pattern I used to generate the orignal String SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE MMMM YYYY h:mm:ss a"); but you are correct DateTimeFormatter has different formatting requirements than SimpleDateFormat. Thanks! – S.O.S Sep 12 '19 at 04:15
  • @S.O.S `SimpleDateFormat` is notoriously troublesome and long outdated, you should not use it at all. In any case, it has the same distinction between lowercase and uppercase Y. For formatting the result will be the same in 98 or 99 % of cases, so you’re not likely to discover the error right away, but using incorrect case is still an error. – Ole V.V. Sep 12 '19 at 06:27