Raushan Raushan - 1 year ago 73
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");

date1 = sdf.parse("12:45");
date2 = sdf.parse("13:00");

date1 = sdf.parse("13:00");
date2 = sdf.parse("13:15");

Output in all the three cases respectively:

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

Answer Source

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"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download