This is because those old Date
and SimpleDateFormat
are troublesome.
What happens here is that, because hh
is used, the number 12
'overflows' to 0
here. The code which actually does this is found in the SimpleDateFormat
source code, in the subParse
method.
You should use HH
. And while you're at it – you should use modern Java Date and Time API from the java.time
package:
String startTimeStr = "11:00";
String endTimeStr = "12:00";
LocalTime startTime = LocalTime.parse(startTimeStr);
LocalTime endTime = LocalTime.parse(endTimeStr);
// No need for a explicit formatting string, because the default is used here,
// which is HH:mm[:ss[.nnnnnnnnn]]
if (endTime.isAfter(startTime)) {
System.out.println("If");
}
else {
System.out.println("Else");
}
But even if you used an explicit DateTimeFormatter
with the pattern string hh:mm
, then a DateTimeException
would have been thrown because the value to be parsed were ambiguous. 11:00 and 12:00 in a twelve-hour clock could mean two things: either AM or PM. The parser by default doesn't like ambiguous values, so instead of just choosing one and moving on, causing confusion to everyone, the authors decided to immediately stop the parsing process and throw an exception. The following code shows this:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm");
String startTimeStr = "11:00";
LocalTime startTime = LocalTime.parse(startTimeStr, formatter);