Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

java - JDK8: unable to parse LocalTime

I managed to parse a String to a LocalDate object:

DateTimeFormatter f1=DateTimeFormatter.ofPattern("dd MM yyyy");
LocalDate d=LocalDate.parse("26 08 1984",f1);
System.out.println(d); //prints "1984-08-26"

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);

Throws a 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

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you use a specific format, according to API:

The string must represent a valid time and is parsed using DateTimeFormatter.ISO_LOCAL_TIME.

hh mm 

for 24h must be

HH mm

or for 12h

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...