9

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
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Kaizar Laxmidhar
  • 859
  • 1
  • 17
  • 38
  • 1
    Duplicate of _[Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)](http://stackoverflow.com/questions/27454025/unable-to-obtain-localdatetime-from-temporalaccessor-when-parsing-localdatetime)_. – Diti Oct 05 '16 at 09:28
  • @Diti 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. – Kaizar Laxmidhar Oct 05 '16 at 09:34
  • 3
    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. – Tunaki Oct 05 '16 at 09:36
  • @Tunaki@Diti Thanks for clarifying, that works! – Kaizar Laxmidhar Oct 05 '16 at 09:42

2 Answers2

16

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
greg-449
  • 109,219
  • 232
  • 102
  • 145
0

LocalTime.parse("04:17");