Tuesday, February 27, 2007

Ruminating on dates, DST and days-between calculations

In one of my programs, I needed to calculate the difference between 2 dates in days. Ironically I could not find any method for the same in the core Java API of Calendar and Date.

So, I decided to write a utility method for the same. But then it struck me that I need to take care of DST and leap seconds. Googling around led me to a interesting journey of Atomic clocks, Quartz clocks, leap secs, etc.

Some cool links to get started with the concepts:

Finally the algorithm I used to calculate the days-between 2 dates was:
1. Get the UTC time of both dates (imp if dates are from different locales)
2. Set the time on both dates as 12 noon. (good practice as it avoids DST and leap sec issues)
3. Calculate the milli-sec difference between the dates.
4. Divide the difference with 24*60*60 and take a Math.abs