Parse clock time in java 8
Asked Answered
A

2

10

I wonder is it possible to parse clock time hour:minute:second in Java 8?

e.g.

final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
final String str = "12:22:10";
final LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

I tried but get this exception:

Exception in thread "main" java.time.format.DateTimeParseException: Text '12:22:10' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 12:22:10 of type java.time.format.Parsed
Alphonso answered 5/10, 2016 at 9:24 Comment(4)
Duplicate of Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8).Lontson
@Lontson Don't think it's the same issue. The link you have provided is parsing a bare date without time. Where as my issue is parsing bare time without date.Alphonso
Fundamentally, it's the same issue: you're trying to parse into a LocalDateTime but you have no date, so which date is supposed to be parsed? Parse into a LocalTime instead, that will work.Monolatry
@Monolatry@Lontson Thanks for clarifying, that works!Alphonso
I
18

LocalTime.parse

Since you only have a time use the LocalTime class. No need to define a formatting pattern in your case.

String str = "12:22:10";
LocalTime time = LocalTime.parse(str);

See that code run live at IdeOne.com.

See Oracle Tutorial for more info.

Intramuscular answered 5/10, 2016 at 9:38 Comment(2)
Since it's a standard format, you can simply use LocalTime.parse(str);.Manchu
FYI, see a chart I made comparing the various date-time types including LocalTime: i.sstatic.net/WyAl2.pngSpit
P
2

LocalTime.parse("04:17");

Parlous answered 1/8, 2021 at 20:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.