Raushan Raushan - 1 month ago 14
Java Question

Time difference gives wrong value

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.

Answer

First and biggest error:

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

Another more subtile error:

Using SimpleDateFormat is errorprone because it implicitly uses a timezone (and the result could be changed by daylight-saving 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 in Java-8:

ChronoUnit.MINUTES.between(LocalTime.parse("11:45"), LocalTime.parse("12:00"))
Comments