Search code examples
javadatedatetimesimpledateformatdate-comparison

Datetime comparison is giving incorrect result


This code should give false since 11:49 is before 12:07. But code is returning true.

If I change 12:07 to 13:00 it gives false which is correct. I have no idea what is wrong with 12:07. Am I missing something? I tried compareTo and giveTime methods as well with same results.

SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm");
System.out.println(format.parse("5/31/2018 11:49").after(format.parse("5/31/2018 12:07")));

Solution

  • hh (ranges 1-12), 12:07 is parsed as 00:07:

    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm");
    System.out.println(format.parse("5/31/2018 00:07").equals(format.parse("5/31/2018 12:07")));  // true
    

    Use HH (ranges 0-23) instead, it will produce desired result:

    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm");
    System.out.println(format.parse("5/31/2018 11:49").after(format.parse("5/31/2018 12:07"))); // false