Formula to calculate difference between two dates
I am working on getting date difference I have a formula to calculate it as follows
$$365\cdot\mathrm{year} + \frac{\mathrm{year}}4 - \frac{\mathrm{year}}{100} + \frac{\mathrm{year}}{400} + \mathrm{date} + \frac{153\cdot \mathrm{month}+8}5$$
but its not working on leap years like
if dates are 1-1-2012 and 1-1-2013 the difference should be 366 days but its giving 365.
where am I wrong?
$\endgroup$ 53 Answers
$\begingroup$This problem has been addressed six weeks ago on this site. I give you the link to the post and answers.
It is not a trivial problem at all (in particular because of the leap years) and I think that the easiest way to solve it is to go through Julian day numbers and perform substraction. Programming this is quite simple (if you need a piece of code, I could make one for you).
Added later
Searching in my notes, I found something (I do not remember where in the Internet) that I put between quotes (I put in bold what I think important) :
"First of all, since February is an especially short month, it is normally better to consider January and February the 13th and 14th months of the previous year. So first, if the month is 1 or 2, then you add 12 to the month and subtract 1 from the year. Then the day is
365*year + year/4 - year/100 + year/400 + date + (153*month+8)/5
where all of the divisions are rounded DOWN to the nearest integer .
Do this for both dates, and subtract."
Do not forget to use the floor of the result of any division.
$\endgroup$ 2 $\begingroup$Use this formula :
First convert both the dates to number of days
Before using the below formula - use these calculations
If Month <= 2, then subtract 1 from Year ( if mm <=2 then Year = Year - 1 else Year = Year)
If Month <= 2, then add 13 to month or add 1 to month ( if mm <=2 then mm = mm+13 else mm = mm+1)
Number of Days = ${(1461 * Year)\over4} + {(153 * Month)\over5} + Day $
Using the above formula, you will have the number of days.
Now do the same for the same for the second date.
Then Difference = Days2 - Days1 will give you the difference between 2 dates.
$\endgroup$ $\begingroup$if m <=2
then m = m+12, y = y-1
no_of_days = (146097*y)/400 + (153*m + 8)/5 + dDo this for both dates and then subtract.After subtracting you will get the number of days between two dates (excluding the end date)
$\endgroup$ 1