Raushan
Raushan

Reputation: 244

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.

Upvotes: 0

Views: 271

Answers (1)

Meno Hochschild
Meno Hochschild

Reputation: 44061

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"))

Upvotes: 3

Related Questions