Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 676
Yury Avatar asked Dec 17 '22 13:12

Yury


2 Answers

The default formatter expects an ISO format, which uses 2 digits for each of the hours, minutes and seconds.

If you want to parse the time you showed, which only has one digit for hours, you will need to provide a custom formatter (note the single H):

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("H:mm:ss");
LocalTime t = LocalTime.parse(times.get(i), formatter);
like image 184
assylias Avatar answered Dec 30 '22 03:12

assylias


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.

like image 26
cegredev Avatar answered Dec 30 '22 03:12

cegredev