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