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

孤街浪徒 提交于 2021-02-05 07:38:21

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!