Friday, March 12, 2010

Java Date Math

Daylight savings time happens this weekend which provides a certain moment of truth for applications which must calculate the days between dates.

There are 86400 seconds in 24 hours. A typical solution might be to convert the days to seconds since the epoch, then subtract them yielding the difference between days in seconds, then divide by 86400 to obtain the days.

This algorithm fails because not all days are of the same duration.

Julian dates offer a solution. Each day has a unique integer value and caculating the difference is a simple matter of subtraction. Astronomers also use a "julian date" - which represents time and date as a float. (Note: if an integer julian date triggers your Aspergers, please spare me the email. I know the difference).

Example Gregorian/Julian routines are available in Numerical Recipes. Here is a Java class which performs the same functions.

To calculate the days between two dates:

DateMath dm = new DateMath();
int jd1 = dm.gregorianToJulian(calendar1);
int jd2 = dm.gregorianToJulian(calendar2);
int delta = jd1-jd2;