Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 397
SMBiggs Avatar asked Nov 02 '12 15:11

SMBiggs


People also ask

How do I compare Calendar dates in Java?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.

How do you check whether the given date is between two dates in Java?

We can use the simple isBefore , isAfter and isEqual to check if a date is within a certain date range; for example, the below program check if a LocalDate is within the January of 2020. startDate : 2020-01-01 endDate : 2020-01-31 testDate : 2020-01-01 testDate is within the date range.


1 Answers

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();
like image 194
Arne Burmeister Avatar answered Nov 09 '22 12:11

Arne Burmeister