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?
A time without a time-zone in the ISO-8601 calendar system, such as 10:15:30 . LocalTime is an immutable date-time object that represents a time, often viewed as hour-minute-second. Time is represented to nanosecond precision. For example, the value "13:45.30. 123456789" can be stored in a LocalTime .
LocalTime is an immutable class whose instance represents a time in the human readable format. It's default format is hh:mm:ss. zzz.
parse() method of a LocalTime class used to get an instance of LocalTime from a string such as '2018-10-23' passed as parameter using a specific formatter. The date-time is parsed using a specific formatter.
Parsing String to LocalDate The first argument is the string representing the date. And the second optional argument is an instance of DateTimeFormatter specifying any custom pattern. //Default pattern is yyyy-MM-dd LocalDate today = LocalDate. parse("2019-03-29"); System.
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:
Use DateTimeFormatter.ofPattern("kk mm")
; for 12 hour clock or DateTimeFormatter.ofPattern("HH mm")
for 24 hour clock
If you want to parse time with hh
you must combine it wih a
where you define AM or PM:
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("hh mm a");
LocalTime t = LocalTime.parse("11 08 AM", f2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With