I want to create a one utility method that parses custom time strings like: 14h , 17h30.
I tried to use LocalTime.ofPattern() method using various pattern combination but I keep getting a DateTimeParseException
Edit:
I tried the following:
This throws an exception when the time is 14h
LocalTime time = LocalTime.parse("14h", DateTimeFormatter.ofPattern("k'h'm"));
And this also throws an exception for 14h30
LocalTime time = LocalTime.parse("9h30", DateTimeFormatter.ofPattern("k'h'"));
I learned from the comment that I can use the catch block to handle all the patterns but I wonder if there is a java time API that can accept a list of patterns
>Solution :
I would utilize a DateTimeFormatterBuilder here in order to create a flexible DateTimeFormatter that parses a wide variety of input.
Create a List<String> of some possible test values, then loop through them and try to parse each one with that formatter.
Here’s an example:
public static void main(String[] args) {
// prepare some test values (don't know if all of them actually apply to your problem)
List<String> times = List.of("17h", "17h30", "4h", "4h59", "09h", "09h21");
// prepare a DateTimeFormatter with optional minutes of hour and a fixed 'h'
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendPattern("H")
.appendLiteral('h')
.optionalStart()
.appendPattern("m")
.optionalEnd()
.toFormatter(Locale.ENGLISH);
times.forEach(time -> {
try {
// then try to parse each test value
LocalTime localTime = LocalTime.parse(time, dtf);
// and print it if no exception was thrown
System.out.println(localTime.format(DateTimeFormatter.ISO_LOCAL_TIME));
} catch (DateTimeParseException dtpEx) {
// in case of an exception, print the value that could not be parsed
String msg = String.format("Could not parse %s", time);
System.err.println(msg);
}
});
}
Output:
17:00:00
17:30:00
04:00:00
04:59:00
09:00:00
09:21:00
Please note: I used the symbol H for hour of day, but if your possible values really use k for clock-hour of day, then simply replace the H for k. The edge cases would be 00h and 24h. Consider involving them in your test cases 😉