java LocalDateTime解析具有模式MM/d/yyyy的日期的异常HH:mm:ss a

Rav*_*avo 2 java java-date

我在执行下面的代码时遇到异常我正在使用java datetime API.

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);
Run Code Online (Sandbox Code Playgroud)

以下异常即将来临

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)
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

您的模式指定"HH",它是一天中的0-padded 24小时制.你想要h:非零填充,以及"每小时上午时钟"(每天12小时).

你几乎不会想要HHH采用相同的模式a.

一般来说,当遇到这样的问题时,你应该非常仔细地查看你的模式,并将它与文档中的描述进行比较.