无法将 hhmmss 格式的时间解析为 Java 中的 LocalTime

问题描述 投票:0回答:2

我正在尝试在java中按如下方式解析'093000':

LocalTime parsed = LocalTime.parse("093000", DateTimeFormatter.ofPattern("hhmmss"));

但是我遇到了这个异常并且似乎无法弄清楚

Exception in thread "main" java.time.format.DateTimeParseException: Text '093000' could not be parsed: Unable to obtain LocalTime from TemporalAccessor: {MinuteOfHour=30, HourOfAmPm=9, SecondOfMinute=0, MicroOfSecond=0, MilliOfSecond=0, NanoOfSecond=0},ISO of type java.time.format.Parsed
at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2023)

与 AM/PM 有关吗?

java java-time
2个回答
1
投票

请尝试使用

HHmmss
代替
hhmmss

LocalTime parsed = LocalTime.parse("093000", DateTimeFormatter.ofPattern("HHmmss"));

0
投票

h
是“上午/下午”字段的模式字符,而不是“一天中的小时”字段,这可能是您想要的。

由于

09
被解释为“上午/下午的小时”字段,因此现在是上午 9 点还是晚上 9 点是不明确的,因此解析失败。如果您希望
09
表示上午 9 点,
21
表示晚上 9 点,则应使用
H
模式字符。

DateTimeFormatter.ofPattern("HHmmss")

另请参阅文档中的模式字符列表。

© www.soinside.com 2019 - 2024. All rights reserved.