The solution provided in the accepted answer works only if you execute it on a machine with ENGLISH
as the default Locale
; it will fail otherwise.
Never use SimpleDateFormat
or DateTimeFormatter
without a Locale because they are Locale
-sensitive. Use the following one to avoid failure due to the default Locale
not matching the input.
DateTimeFormatter.ofPattern("h[:mm]a", Locale.ENGLISH);
Demo:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.stream.Stream;
public class Main {
public static void main(String args[]) {
DateTimeFormatter parser = DateTimeFormatter.ofPattern("h[:mm]a", Locale.ENGLISH);
Stream.of(
"10AM",
"12:30PM",
"2:47PM",
"1:09AM",
"5PM"
)
.map(s -> LocalTime.parse(s, parser))
.forEach(System.out::println);
// See how it can fail with other locales
// Assuming the default Locale of the system is Locale.CHINA,
// DateTimeFormatter.ofPattern("h[:mm]a") will automatically be turned into
// DateTimeFormatter.ofPattern("h[:mm]a", Locale.CHINA) causig the parsing to
// fail
DateTimeFormatter errorProneParser = DateTimeFormatter.ofPattern("h[:mm]a", Locale.CHINA);
LocalTime localTime = LocalTime.parse("10AM", errorProneParser);
}
}
Output:
10:00
12:30
14:47
01:09
17:00
Exception in thread "main" java.time.format.DateTimeParseException: Text '10AM' could not be parsed at index 2
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2052)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1954)
at java.base/java.time.LocalTime.parse(LocalTime.java:465)
at Main.main(Main.java:24)
LocalDateTime
, that's only aLocalTime
. – Sisyphean