Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse HH:mm:ss and H:mm:ss for LocalTime using single DateTimeFormatter in java8

I am trying to parse 08:24:55 (HH:mm:ss) and 8:24:55 (H:mm:ss) using LocalTime.parse() method in java 8. Below Code successfully get's executed and prints 08:24:55:

LocalTime time=LocalTime.parse("08:24:55", DateTimeFormatter.ofPattern("HH:mm:ss"));
System.out.println(time);

but the same set of code fails for input 8:24:55 and throws error:

Exception in thread "main" java.time.format.DateTimeParseException: Text '8:24:55' could not be parsed at index 0

Any suggestions what could be done to handle both scenarios?

like image 735
Nitishkumar Singh Avatar asked Nov 27 '17 13:11

Nitishkumar Singh


People also ask

How do I use DateTimeFormatter with date?

DateTimeFormatter fmt = DateTimeFormatter. ofPattern("yyyy-MM-dd'T'HH:mm:ss"); System. out. println(ldt.

How do I parse LocalDateTime?

Parsing date and time To create a LocalDateTime object from a string you can use the static LocalDateTime. parse() method. It takes a string and a DateTimeFormatter as parameter. The DateTimeFormatter is used to specify the date/time pattern.

Is Java time format DateTimeFormatter thread safe?

DateTimeFormatter is a formatter that is used to print and parse date-time objects. It has been introduced in Java 8. DateTimeFormatter is immutable and thread-safe.


2 Answers

Use just one H in your pattern:

LocalTime time= LocalTime.parse("08:24:55", DateTimeFormatter.ofPattern("H:mm:ss"));

Output:

08:24:55

like image 102
Juan Carlos Mendoza Avatar answered Oct 23 '22 17:10

Juan Carlos Mendoza


You can make some "times" optional via:

 DateTimeFormatter.ofPattern("H[H]:mm:ss")
like image 1
Eugene Avatar answered Oct 23 '22 19:10

Eugene