0

I am trying to calculate the difference between two dates. The difference consist of remaining Days, Hours, Minutes, Seconds.

I'm using this method:

public static void computeDiff(Date date2) {
        Date date1 = new Date();
        long diffInMillies = date2.getTime() - date1.getTime();

        long milliesRest = diffInMillies;

        for ( TimeUnit unit : timeUnitsArrayList ) {
            long diff = unit.convert(milliesRest, TimeUnit.MILLISECONDS);
            long diffInMilliesForUnit = unit.toMillis(diff);
            milliesRest -= diffInMilliesForUnit;
            result.put(unit, diff);
        }
}

/*
TimeUnit = java.util.concurrent.TimeUnit
timeUnitsArrayList = A list with units: DAYS, HOURS, MINUTES, SECONDS
date1 = java.util.Date (date now)
date2 = java.util.Date (a date with time 00:00:00)
*/

I'm giving an example: If i want the difference between today and and 20 March 2015, the difference will be ok (8 days, X hours, Y minutes, Z seconds), but if i choose an older date like 20 April 2015 the difference will be 39 days (ok), X - 1 hours (which isn't ok because is calculating wrong), Y minutes (ok), Z seconds(ok).

Is a Java bug or a bug in my code? Because if i choose an earlier date, the hours are ok, but if i choose an older date i get the hours wrong (one less hour)

Thank you

Ghita
  • 23
  • 8
  • possible duplicate of [Calculating the Difference Between Two Java Date Instances](http://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances) – Scary Wombat Mar 11 '15 at 08:10
  • daylight saving time –  Mar 11 '15 at 08:11
  • It would really help if you'd provide a concrete example in the form of a short but complete program demonstrating the problem, explaining *why* you expect the result to be a certain way. It sounds like this is almost certainly a daylight saving issue, but it's hard to give an answer without more information. – Jon Skeet Mar 11 '15 at 08:12
  • Thank you Rafael Osipov. Now everything makes sense. – Ghita Mar 11 '15 at 08:20

1 Answers1

3

This is most probably an issue with the switch to daylight saving time - in central europe the change is on 29 March, so in your timezone (wherever that is) it might be similar and would account for the 1 hour.

piet.t
  • 11,718
  • 21
  • 43
  • 52