JDK8:无法解析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.(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); 

LocalTime::from文档说

转换使用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"); 

您的模式必须至少包含其中一个字符串才能在内部TemporalAccessor获取NANO_OF_DAY字段,从中可以构造NANO_OF_DAY

您需要在模式中使用大写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