java LocalDateTime解析具有模式MM/d/yyyy HH:mm:ss的日期的异常 [英] java LocalDateTime parsing exception for date having pattern MM/d/yyyy HH:mm:ss a

查看:45
本文介绍了java LocalDateTime解析具有模式MM/d/yyyy HH:mm:ss的日期的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Java日期时间API执行以下代码时遇到异常.

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);

以下异常即将到来

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)

推荐答案

您的模式指定"HH",它是一天中的零填充24小时.您需要 h :非零填充和"clock-hour-of-am-pm"(一天中的12小时).

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).

您几乎从不想要以与 a 相同的方式使用 HH H .

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.

这篇关于java LocalDateTime解析具有模式MM/d/yyyy HH:mm:ss的日期的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆