Java Calendar: Getting Difference Between Two Dates/Times - Off by One

SMBiggs picture SMBiggs · Nov 2, 2012 · Viewed 55.2k times · Source

I have seen many questions and answers on this topic, but none addressed my particular problem. I extended the java Calendar class (standard--no third party libraries), and needed to find the difference in days between two arbitrary dates.

Method:

  1. Change the time of both dates to midnight.
  2. Convert the dates to milliseconds.
  3. Find the difference between the two dates.
  4. Divide the result by the number of milliseconds in a day (24 * 60 * 60 * 1000).
  5. The result should be the difference in days.

And it sometimes is, and it sometimes isn't. Even tests on the same date can be off by one. What's going on?

Answer

Arne Burmeister picture Arne Burmeister · Nov 2, 2012

The Joda Time Library has very good support for such problems:

LocalDate d1 = new LocalDate(calendar1.getTimeInMillis());
LocalDate d2 = new LocalDate(calendar2.getTimeInMillis());
int days = Days.daysBetween(d1, d2).getDays();

UPDATE (feedback from @basil-bourque):

As of Java 8 the new time library java.time has been introduced, now a similar option without external dependencies is available:

int days = Duration.between(calendar1.toInstant(), calendar2.toInstant()).toDays();