I would think you’re after something like the following:
String timeString1 = "2:00 PM";
String timeString2 = "9:00 AM";
DateTimeFormatter timeFormatParser
= DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
LocalTime time1 = LocalTime.parse(timeString1, timeFormatParser);
LocalTime time2 = LocalTime.parse(timeString2, timeFormatParser);
if (time1.isAfter(time2)) {
System.out.println("After");
}
With the strings in my example the code does print After
. If your original time strings have a different format, I hope you can modify the format pattern string accordingly, otherwise follow up in a comment. Or maybe better, edit your question to specify your strings precisely. The letters you can use are documented here. Please be aware that the format pattern is case sensitive.
My DateTimeFormatter
expects AM
or PM
in uppercase. If your strings have them in lowercase, there are a couple of options:
- The simple:
timeString1 = timeString1.toUpperCase(Locale.ENGLISH);
and similarly for timeString2
.
- The more general but also more complex: Use a
DateTimeFormatterBuilder
to build a non-case-sensitive DateTimeFormatter
.
PS Before the modern Java date and time API that I am using came out in 2014, one would often use a class called SimpleDateFormat
to parse into a Date
object. Nowadays stay away from that. The newer classes have shown to be considerably nicer to work with and more programmer friendly.