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

Ravo :

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)
Jon Skeet :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113512&siteId=1