Nitishkumar Singh
Nitishkumar Singh

Reputation: 1839

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?

Upvotes: 8

Views: 17657

Answers (2)

Eugene
Eugene

Reputation: 120968

You can make some "times" optional via:

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

Upvotes: 1

Juan Carlos Mendoza
Juan Carlos Mendoza

Reputation: 5814

Use just one H in your pattern:

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

Output:

08:24:55

Upvotes: 14

Related Questions