当我尝试解析 LocalDateTime(使用 JDK 8)时出现意外异常。
DateTimeFormatter DTF = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm");
String dateStr = LocalDateTime.now().format(DTF);
// => dateStr = 03/03/2023 01:56
LocalDateTime date = LocalDateTime.parse(dateStr, DTF);
// => throw DateTimeParseException
我不明白为什么 parse 方法抛出 DateTimeParseException 而 format 方法正常工作。我正在使用相同的 DateTimeFormatter 将日期格式化为字符串。
线程“main”中的异常 java.time.format.DateTimeParseException:无法解析文本“03/03/2023 01:56”:无法从 TemporalAccessor 获取 LocalDateTime:{MinuteOfHour=56,HourOfAmPm=1},ISO 已解决到 2023-03-03 类型的 java.time.format.Parsed 在 java.time.format.DateTimeFormatter.createError (DateTimeFormatter.java:1920) 在 java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855) 在 java.time.LocalDateTime.parse(LocalDateTime.java:492)
你有什么想法吗?
我为一天中的小时(0-23)更改了 DateTimeFormatter 的模式。
DateTimeFormatter DTF = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
=> 这很好用。
为什么它不适用于时钟时间 am-pm (1-12)?
正如@OH GOD SPIDERS 所解释的,我需要添加
a
来指定上午/下午或使用 HH
来指定 24 小时格式。
所以要使用 clock-hour-of-am-pm (1-12) 格式,添加
a
:
DateTimeFormatter DTF = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mma");
或使用一天中的小时格式 (0-23),将
hh
更改为 HH
:
DateTimeFormatter DTF = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");