JDK8:无法解析LocalTime [英] JDK8: unable to parse LocalTime
本文介绍了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"
但我不能用<$ c $做同样的事情C>本地时间。这段代码:
But I cannot do the same with LocalTime
. This piece of code:
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 :
If you use a specific format, according to API:
字符串必须表示有效时间,并使用
DateTimeFormatter.ISO_LOCAL_TIME
。
hh mm
24小时必须
HH mm
或12小时
kk mm
处理后的格式必须具备以下条件:
The handled formats must have this conditions:
- 每小时的两位数字。这是预先填充零以确保两位数。
- 冒号
- 小时的两位数。这是预先填充零以确保两位数。
- 如果第二分钟不可用,则表示格式已完成。
- 冒号
- 二分钟的两位数字。这是预先填充零以确保两位数。
- 如果纳秒级为零或不可用,则表示格式已完成。
- 小数点
- 纳秒级的一到九位数。根据需要输出许多数字。
- Two digits for the hour-of-day. This is pre-padded by zero to ensure two digits.
- A colon
- Two digits for the minute-of-hour. This is pre-padded by zero to ensure two digits.
- If the second-of-minute is not available then the format is complete.
- A colon
- Two digits for the second-of-minute. This is pre-padded by zero to ensure two digits.
- If the nano-of-second is zero or not available then the format is complete.
- A decimal point
- One to nine digits for the nano-of-second. As many digits will be output as required.
这篇关于JDK8:无法解析LocalTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文