How can I get the number of days that have elapsed between two Date objects?
If you want to find out the number of 24-hour periods between two Date objects d1 and d2 (d2 > d1) then you would do this:
double days = (d2.getTime()-d1.getTime())/1000/60/60/24;
Sometimes this can cause difficulties, especially in countries that have a form of daylight savings time. For example, in the U.S., there is one day in the Fall which has 25 hours, and one day in the Spring which has 23 hours. An elapsed-number-of-days calculation on Dates falling on one of these days may not give the answer you expect.
Anyway, that's the easy way, and if you're satisfied with that, then read no further.
If, on the other hand, you mean the number of midnight-crossings (so that the number of days elapsed between 11:00 PM and 1:00 AM the next day is 1) then you're better off using the Calendar class and computing the Julian Day.
By the way, don't mistake the Julian Day for the Julian Calendar. The two are different and named after different "Julians".
The Julian Day is defined as the number of days elapsed since Nov 24, 4714 BC, 12:00 GMT Gregorian. The year was chosen as being sufficiently in the past so as not to have negative Julian Days, the date was chosen because of the (in that year) 37-day difference between the Julian and Gregorian calendars (Nov 24, 4714 BC Gregorian would be Jan 1, 4713 BC Julian), and the time was chosen because astronomers do their work at night, and it would be a little confusing (to them) to have the Julian Day change in the middle of their work. (I could be wrong)
Anyway, the algorithm for computing the Julian Day from a Gregorian or Julian calendar date for years 400 AD and above is as follows:
Let the date be Y, M, D, where Y is the AD year, M is the month (January=1, December=12), and D is the day (1-31).
For the following calculations, use integer arithmetic (i.e. lop off the fractional part of any result).
If M==1 or M==2 then Y--, M+=12. Let A = Y/100 Let B = A/4 Let C = 2-A-B (or C=0 if you're using the Julian calendar) Let E = 365.25*(Y+4716) Let F = 30.6001*(M+1) Julian Day = C+D+E+F-1524.5
There would be a further adjustment for the time of day, but we're not looking at that. If you want your Julian Days to start at midnight, subtract 1524 rather than 1524.5.
And so, your number-of-days-elapsed calculation would look like this:
Calendar c1 = new GregorianCalendar(); Calendar c2 = new GregorianCalendar(); c1.setTime(d1); c2.setTime(d2); long j1 = julian_day(c1.get(YEAR), c1.get(MONTH)+1, c1.get(DAY)); long j2 = julian_day(c2.get(YEAR), c2.get(MONTH)+1, c2.get(DAY)); long days_elapsed = j2-j1;
And this would properly calculate the number of midnight-crossings between 11:00 PM on one day and 1:00 AM the next day.
You can get a little more information about the Julian Day calculations here.