First of all, the error you get is caused by the H
in your pattern, which parses hours in 24-hour format and gets into trouble if you put an a
(for AM/PM) at the end of the pattern.
You can use java.time
to parse the String
s to LocalTime
s using a DateTimeFormatter
that considers both of the patterns:
public static void main(String[] args) {
// define a formatter that considers two patterns
DateTimeFormatter parser = DateTimeFormatter.ofPattern("[h:mma][hh:mma]");
// provide example time strings
String firstTime = "2:37PM";
String secondTime = "02:37PM";
// parse them both using the formatter defined above
LocalTime firstLocalTime = LocalTime.parse(firstTime, parser);
LocalTime secondLocalTime = LocalTime.parse(secondTime, parser);
// print the results
System.out.println("First:\t" + firstLocalTime.format(DateTimeFormatter.ISO_TIME));
System.out.println("Second:\t" + secondLocalTime.format(DateTimeFormatter.ISO_TIME));
}
The output of this is
First: 14:37:00
Second: 14:37:00
But it turned out you only need one pattern (which is better to have than two in a DateTimeFormatter
anyway) because the h
is able to parse hours of one or two digits. So the following code produces exactly the same output as the one above:
public static void main(String[] args) {
// define a formatter that considers hours consisting of one or two digits plus AM/PM
DateTimeFormatter parser = DateTimeFormatter.ofPattern("h:mma");
// provide example time strings
String firstTime = "2:37PM";
String secondTime = "02:37PM";
// parse them both using the formatter defined above
LocalTime firstLocalTime = LocalTime.parse(firstTime, parser);
LocalTime secondLocalTime = LocalTime.parse(secondTime, parser);
// print the results
System.out.println("First:\t" + firstLocalTime.format(DateTimeFormatter.ISO_TIME));
System.out.println("Second:\t" + secondLocalTime.format(DateTimeFormatter.ISO_TIME));
}