JDK8:无法解析LocalTime

Lui*_*ese 17 java date-parsing java-8

我设法解析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"
Run Code Online (Sandbox Code Playgroud)

但我不能这样做LocalTime.这段代码:

DateTimeFormatter f2=DateTimeFormatter.ofPattern("hh mm");
LocalTime t=LocalTime.parse("11 08",f2); //exception here
System.out.println(t);
Run Code Online (Sandbox Code Playgroud)

抛出一个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
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Jor*_*lla 19

如果您使用特定格式,则根据API:

该字符串必须表示有效时间并使用进行解析DateTimeFormatter.ISO_LOCAL_TIME.

hh mm 
Run Code Online (Sandbox Code Playgroud)

必须24小时

HH mm
Run Code Online (Sandbox Code Playgroud)

或者持续12小时

kk mm
Run Code Online (Sandbox Code Playgroud)

处理的格式必须具备以下条件:

  • 两个数字的小时.这是预先填充零以确保两位数.
  • 结肠
  • 分钟的两位数.这是预先填充零以确保两位数.
  • 如果第二分钟不可用,则格式完成.
  • 结肠
  • 二分钟的两位数.这是预先填充零以确保两位数.
  • 如果纳秒级为零或不可用,则格式完成.
  • 小数点
  • 纳秒级的一到九位数.将根据需要输出许多数字.

  • 这很有趣,我觉得我可以无限制地混淆元素的顺序...... (3认同)