Search code examples
javadatecalendardatediff

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


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?


Solution

  • As suggested by other users, you need to also set the millisecond value of the calendars to zero to compare only the dates. This can be achieved with the following code snippet:

    someCalendar.set(Calendar.MILLISECOND, 0)
    

    Also, note that timezone changes (e.g. moving from winter time to summer time) may mean there is more or less than 86,400,000 ms in a day.