public static final long MILLIS_IN_DAY = 1000*60*60*24;

public long getDaysBetween(Calendar c1, Calendar c2)
{
        long c1Normalized = c1.getTime().getTime() + 
                          c1.get(Calendar.ZONE_OFFSET) +
                          c1.get(Calendar.DST_OFFSET);

        long c2Normalized = c2.getTime().getTime() + 
                          c2.get(Calendar.ZONE_OFFSET) +
                          c2.get(Calendar.DST_OFFSET);

        long diff = c1Normalized - c2Normalized;

        long numDays = diff / MILLIS_IN_DAY;

        return numDays;
}

A common mistake most people make is to ignore daylight savings
time when trying to compute the number of days between two Calendar
dates.  If you cross the DST boundary when the clock jumps forward,
just subtracting the date objects and dividing will end up giving you
an answer that is off by 1 day.  This happens because the clock jumps
ahead, and 00:00 EDT is actually 11:00 EST on the previous day, so the
number of hours is off by 1, and thus the calculation doesn't end up working
properly.  The other thing i'm doing here is to convert to GMT time,
allowing
for the two Calendar objects to have different timezones.

We could have similar methods for getHoursBetween and so forth.  Months
would be a bit more complicated of an algorithm.

Reply via email to