In order to do date calculations we must translate any given date specified by the three components year, month, and day, into an integer day number. If we choose a base date for day 0 wisely, calculations will be simplified. For this method the base date will be March 1, year 0. Note that this year 0 is not the Gregorian year 0, it is a reference date only. However, calculations involving dates after the establishment of the Gregorian calendar will be correct.
365.0000 + 0.2500 - 0.0100 + 0.0025Now the number of days in y years is:
365 + 1/4 - 1/100 + 1/400
d = 365y + y/4 - y/100 + y/400 (1)
If we now make this a discrete function by considering integer d's and disregarding remainders, we have:
d = 365y + int(y/4) - int(y/100) + int(y/400) (2)
Every four years the second term y/4 will add an extra day, but that will be neutralized every century by the third term y/100. However, every four centuries, the leap day will be added after all, as the last term y/400 kicks in. This discrete function is the source of the Gregorian leap year rules. Function (2) approximates the real function (1) very closely, and the two are equal for years divisible by 400. In the intervening years of this 400 year cycle, the error maxima are 1.4775 days in year 303 of the cycle, and -0.72 days in year 96 of the cycle. Because of this error, finding the year given a number of days (the inverse function) is not exact, but we can find a very close approximation. Given d days, the year number can be approximated as
y = d / 365.2425 (3)This will be correct for nearly all dates, except in some cases where d is within the error maxima from a year boundary. When this happens, we can test for it and adjust the year accordingly.
Because the lengths of the months are not the same, and especially because
the length of February is not fixed, it would seem at first to be impossible
to calculate day offsets in a year without looking up tables and checking
for leap years. However, we can get around the problem by defining the
start of our calendar year with March. Numbering the months in this way
has the special advantage that leap days are always added at the end of
the year, and do not change the day offsets for the beginnings of the months.
Using basic linear regression on the month indexes and the day offsets,
we can find functions to map each to the other. Given the month index,
we can calculate the day number for the first of the month from the integer
part of the function
d = f(m) = (306*m + 5)/10:
Now, the inverse function, given the day index into the year, we can calculate the month index by taking the integer part of the function m = f(d) = (100*d + 52)/3060.
The following table shows the values of the function for the first and last days of each month:
m = f(d) = (100*d + 52)/3060
|month||length||index||s=first day||e=last day||f(s)||f(e)|