Search code examples
javatimelocaltimedatetime-parsingtime-format

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


Solution

  • 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.