Skip to content
Advertisement

How to parse time in any format with LocalTime.parse?

I am having trouble using java’s LocalTime to parse a string with hours, minutes, and seconds.

LocalTime t = LocalTime.parse("8:30:17"); // Simplification

This throws the following exception:

Exception in thread “main” java.time.format.DateTimeParseException: Text ‘8:30:17’ could not be parsed at index 0

Advertisement

Answer

You’ll need to pass in a custom DateTimeFormatter like this:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("H:mm:ss");
LocalTime t = LocalTime.parse(times.get(i), formatter);

Take a look at the docs, as the letters you need to use might be different.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement