Ravo
Ravo

Reputation: 41

java LocalDateTime parsing exception for date having pattern MM/d/yyyy HH:mm:ss a

I am getting exception while executing below code i am using java datetime APIs.

String strDate = "12/4/2018 5:26:28 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/d/yyyy HH:mm:ss a", Locale.ENGLISH);
LocalDateTime  localDateTime = LocalDateTime.parse(strDate, formatter);

below exception is coming

Exception in thread "main" java.time.format.DateTimeParseException: Text '12/4/2018 5:26:28 PM' could not be parsed at index 10
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at Test.main(Test.java:20)

Upvotes: 2

Views: 346

Answers (2)

Aukta
Aukta

Reputation: 413

Use hh for 12-hours format and match it up with 05.

    String strDate = "12/4/2018 05:26:27 PM";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/d/yyyy hh:mm:ss a", Locale.ENGLISH);
    LocalDateTime  localDateTime = LocalDateTime.parse(strDate, formatter);

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502236

Your pattern specifies "HH" which is a 0-padded 24-hour hour of day. You want h: non-zero-padded, and "clock-hour-of-am-pm" (12-hour hour of day).

You almost never want HH or H in the same pattern as a.

In general, when you run into problems like this, you should look at your pattern really, really carefully and compare it with the description in the documentation.

Upvotes: 7

Related Questions