我设法将一个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我做错了什么?
发布于 2015-06-10 11:05:13
如果您使用特定的格式,根据API接口
该字符串必须表示有效时间,并使用
DateTimeFormatter.ISO_LOCAL_TIME进行解析。
hh mm 24小时必须
HH mm或12小时
kk mm所处理的格式必须具有以下条件:
发布于 2015-06-10 11:04:00
使用DateTimeFormatter.ofPattern("kk mm");用于12小时时钟或DateTimeFormatter.ofPattern("HH mm")用于24小时时钟
如果要使用hh解析时间,则必须使用定义AM或PM的a组合时间:
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("hh mm a");
LocalTime t = LocalTime.parse("11 08 AM", f2);发布于 2015-06-10 11:35:37
在这种情况下,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字段。使用LocalTime检索DateTimeFormatter的最小允许模式是:
DateTimeFormatter.ofPattern("ha");
DateTimeFormatter.ofPattern("Ka");
DateTimeFormatter.ofPattern("ah");
DateTimeFormatter.ofPattern("aK");
DateTimeFormatter.ofPattern("k");
DateTimeFormatter.ofPattern("H");您的模式必须至少包含其中的一个字符串,才能在内部NANO_OF_DAY中获得一个LocalTime字段,从该字段可以构造LocalTime。
https://stackoverflow.com/questions/30754259
复制相似问题