0

After some debugging, I found that it was because 12:00 was being set to 0:00, but surely if this was a 24-hour clock only 24:00 would be set to 0:00

SimpleDateFormat time_format = new SimpleDateFormat ("hh:mm");

String start_time = "11:00"
String end_time = "12:00"

try {       //parses both times to the date data type
    start_time_format = time_format.parse(start_time);
    end_time_format = time_format.parse(end_time);
} catch (ParseException e) {
    e.printStackTrace();
}


if (end_time_format.after(start_time_format)){
}else{

//how come this is always true

}

taybrie
  • 41
  • 5
  • 1
    Note: don't use `SimpleDateFormat` and `Date`. They're [troublesome](https://stackoverflow.com/questions/1969442/whats-wrong-with-java-date-time-api). Use classes from the `java.time` package. – MC Emperor Feb 02 '21 at 14:16
  • Oh, and you should follow the Java Naming Conventions: variable names and method names are written in camelCase (so no underscores). – MC Emperor Feb 02 '21 at 14:18
  • 6
    Regarding your actual question: use `HH` instead of `hh`. – MC Emperor Feb 02 '21 at 14:18
  • @MCEmperor ok, but surely it was already in a 24-hour format otherwise my 13:00 hour time would be 1:00 not 13:00 – taybrie Feb 02 '21 at 14:27

2 Answers2

3

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);
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
0

Date class of java set 12:00 to 00:00 of the day.therefore new date with 12:00 convert to Jan 01 11:00:00 1970.To avoid this effect you can use "HH:mm" format string.