[英]JDK8: unable to parse LocalTime
我设法将String
解析为LocalDate
对象:
DateTimeFormatter f1=DateTimeFormatter.ofPattern("dd MM yyyy");
LocalDate d=LocalDate.parse("26 08 1984",f1);
System.out.println(d); //prints "1984-08-26"
但我不能对LocalTime
做同样的事情。 这段代码:
DateTimeFormatter f2=DateTimeFormatter.ofPattern("hh mm");
LocalTime t=LocalTime.parse("11 08",f2); //exception here
System.out.println(t);
抛出DateTimeParseException
:
Exception in thread "main" java.time.format.DateTimeParseException: Text '11 08' could not be parsed: Unable to obtain LocalTime from TemporalAccessor: {MinuteOfHour=8, HourOfAmPm=11},ISO of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalTime.parse(Unknown Source)
at com.mui.cert.Main.<init>(Main.java:21)
at com.mui.cert.Main.main(Main.java:12)
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {MinuteOfHour=8, HourOfAmPm=11},ISO of type java.time.format.Parsed
at java.time.LocalTime.from(Unknown Source)
at java.time.LocalTime$$Lambda$15/1854731462.queryFrom(Unknown Source)
at java.time.format.Parsed.query(Unknown Source)
... 4 more
我究竟做错了什么?
如果您使用特定格式,则根据API :
该字符串必须表示有效时间,并使用
DateTimeFormatter.ISO_LOCAL_TIME
进行解析。
hh mm
必须24小时
HH mm
或者持续12小时
kk mm
处理的格式必须具备以下条件:
使用DateTimeFormatter.ofPattern("kk mm")
; 12小时时钟或DateTimeFormatter.ofPattern("HH mm")
24小时制
如果你想用hh
解析时间,你必须将它a
你定义AM或PM a
地方结合起来:
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("hh mm a");
LocalTime t = LocalTime.parse("11 08 AM", f2);
在这种情况下, Unable to obtain LocalTime from TemporalAccessor
意味着它无法确定给定字符串表示的一天中的多少,即没有足够的信息来构造LocalTime
。 在幕后,代码看起来像这个扩展的Java 8版本(它给出了类似的错误):
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("hh mm");
TemporalAccessor temporalAccessor = f2.parse("11 08");
LocalTime t = temporalAccessor.query(LocalTime::from);
System.out.println(t);
转换使用TemporalQueries.localTime()查询,该查询依赖于提取NANO_OF_DAY字段。
您的错误告诉您TemporalAccessor
只有两个字段,这两个字段都不是NANO_OF_DAY
字段。 使用DateTimeFormatter
检索LocalTime
的最小允许模式是:
DateTimeFormatter.ofPattern("ha");
DateTimeFormatter.ofPattern("Ka");
DateTimeFormatter.ofPattern("ah");
DateTimeFormatter.ofPattern("aK");
DateTimeFormatter.ofPattern("k");
DateTimeFormatter.ofPattern("H");
你的模式必须包含这些字符串中的至少一个获得NANO_OF_DAY
在内部场TemporalAccessor
从一个LocalTime
可以构造。
您需要在模式中使用大写HH
DateTimeFormatter f2=DateTimeFormatter.ofPattern("HH mm");
或者这样做,对于clock-hour-of-am-pm
你需要指定它。
这也应该有效
DateTimeFormatter f2=DateTimeFormatter.ofPattern("hh mm a");
LocalTime t=LocalTime.parse("11 08 AM",f2); //exception here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.