2

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)
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Ravo
  • 41
  • 2
  • 7
  • 3
    No. It should be h:mm:ss. Since 5PM would be 17 with H. – JB Nizet Dec 06 '18 at 07:22
  • with pattern h:mm:ss gives me 17 – Ravo Dec 06 '18 at 07:40
  • and that's correct, since 5PM is 17 in 24h. format. If you want to print your LocalDateTime in a specific format, then use a formatter. The toString() method will always give you the ISO format. A LocalDateTime doesn't have a format, just like an int or a double doesn't have a format. – JB Nizet Dec 06 '18 at 07:44
  • Pretty much a possible duplicate of [Difference between java HH:mm and hh:mm on SimpleDateFormat](https://stackoverflow.com/questions/17341214/difference-between-java-hhmm-and-hhmm-on-simpledateformat) and [Java - parse date with AM/PM next to seconds (no space)](https://stackoverflow.com/questions/50859059/java-parse-date-with-am-pm-next-to-seconds-no-space). Those use the troublesome and outdated `SimpleDateFormat`, but otherwise the cause and the fix is the same. – Ole V.V. Dec 06 '18 at 08:05

2 Answers2

7

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

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);
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Aukta
  • 163
  • 1
  • 11