views:

1299

answers:

4

I would like to do simple date calculations in Java. For example, compute the difference in days between to dates (having a 0 time component). Of course you could do a simple substraction of milliseconds, divided by the number of milliseconds per day, which works fine - until daylight saving times enter the scene. I am conscious that different interpretations of the "difference in days" are possible, in particuliar, whether one should take into account the time component or not. Let us assume we have a 0 time component for simplicity.

This kind of calculation seems to be a very common need, and I would find it nice to have a discussion on different approaches to the question.

+8  A: 

I would have a look at the Joda date/time library, and in particular the ReadableInterval class.

Joda makes life a lot easier when manipulating dates/times in Java, and I believe it's the foundation of the new Java JSR 310 wrt. dates/times. i.e. it (or something very similar) will be present in a future version of Java.

Brian Agnew
A: 

Here is an article discussing the use of the Date/Calendar facilities in java to calculate elapsed time.

James Van Huis
A: 

Of course you could do a simple substraction of milliseconds, divided by the number of milliseconds per day, which works fine - until daylight saving times enter the scene.

In which case, you would use rounding to handle this.

Peter Lawrey
What does rounding have to do with it?
Michael Myers
A: 

It looks like Date, Calendar, and DateUtils will do everything you're looking for. http://commons.apache.org/lang/api/org/apache/commons/lang/time/DateUtils.html

DateUtils allows truncating or rounding the time so you can just deal with only the dates. You also mentioned daylight savings time. The main problem is when someone says they did something at 01:30 on a day where there was DST change... which 01:30 was it? The first one or the second? Luckily this can be handled by the Calendar class since it stores the timezone and DST offset. For the specifics on all that, check this out: http://www.xmission.com/~goodhill/dates/deltaDates.html