Get the number of days between two DateTimes
Calculate the number of days between two dates seems really simple, but there are some exceptions. The simplest idea is to substract two DateTime and get the number of days in the resulting TimeSpan. The method doesn't work when the two dates are set with different year or the number of hour are less than 24 (consider 1/7/2005 10:00PM and 1/8/2005 8:00AM).
The solution (in this case applicable to Gregorian calendar) implies to define a date reference (ie. 3/1/1600) and calculates the astronomical day number:
int Days(DateTime time)
{
int d = time.Day;
int m = time.Month;
int y = time.Year;
if ((m -= 2) <= 0)
{
m += 12;
y--;
}
y -= 1600;
int cy = y / 100;
return 365 * y + y / 4 - cy + cy / 4 + 367 * m / 12 + d - 31;
}
Finally, the number of days between two dates is given by the difference of their astronomical days number. The above formula has been attribued to Gauss.