问题
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)
回答1:
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.
回答2:
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);
来源:https://stackoverflow.com/questions/53646377/java-localdatetime-parsing-exception-for-date-having-pattern-mm-d-yyyy-hhmmss