0

I want to get the difference between two time values in Java. Below is the code snippet for the same:

    DateFormat sdf = new SimpleDateFormat("hh:mm");
    Date date1 = sdf.parse("11:45");
    Date date2 = sdf.parse("12:00");
    System.out.println(""+(date2.getTime()-date1.getTime())/60000);

    date1 = sdf.parse("12:45");
    date2 = sdf.parse("13:00");
    System.out.println(""+(date2.getTime()-date1.getTime())/60000);

    date1 = sdf.parse("13:00");
    date2 = sdf.parse("13:15");
    System.out.println(""+(date2.getTime()-date1.getTime())/60000);

Output in all the three cases respectively: Output1:-705 Output2:735 Output3:15

I don't understand why it is taking wrong value as it should be 15 in all the three cases.

Raushan
  • 214
  • 2
  • 3
  • 10

1 Answers1

3

First and biggest error:

You use 12-hour-clock (symbol h), but symbol H would be fine.

Another more subtle error:

Using SimpleDateFormat is error-prone because it implicitly uses a time zone (and the result could be changed by Daylight Saving Time switch, see the case of Europe/London when it was on Summer time in year 1970 - your implicit default year).

Therefore I suggest to use a more modern API. For example the built-in java.time package (Tutorial) in Java SE 8 with its LocalTime and ChronoUnit classes.

ChronoUnit.MINUTES.between(LocalTime.parse("11:45"), LocalTime.parse("12:00"))
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
  • Thanks a lot. You saved my day.. :) – Raushan Oct 24 '16 at 10:25
  • FYI… Much of the java.time functionality is back-ported to Java 6 & 7 in [*ThreeTen-Backport*](http://www.threeten.org/threetenbp/). Further adapted for Android in the [*ThreeTenABP*](https://github.com/JakeWharton/ThreeTenABP) project. – Basil Bourque Oct 24 '16 at 21:41