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

I am trying to parse 08:24:55 (HH: mm: ss) and 8:24:55 (H: mm: ss) using LocalTime.parse()in java 8. Below code is successfully 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 code set is not suitable for entering 8:24:55 and gives an error:

Exception in thread "main" java.time.format.DateTimeParseException: text "8:24:55" cannot be parsed with index 0

Any suggestions on what can be done to handle both scenarios?

+4
source share
2 answers

H :

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

:

8:24:55

+5

"" :

 DateTimeFormatter.ofPattern("H[H]:mm:ss")
+1

Source: https://habr.com/ru/post/1689899/


All Articles