Simple Java Date Calculations

mikemax picture mikemax · Mar 13, 2009 · Viewed 10.5k times · Source

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.

Answer

Brian Agnew picture Brian Agnew · Mar 13, 2009

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.