Date calculation algorithms

Calculate day number from date.

All division is integer division, operator % is modulus.
Given integer y, m, d, calculate day number g as:
function g(y,m,d)
m = (m + 9) % 12
y = y - m/10
return 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )

Calculate date from day number

All division is integer division, operator % is modulus.
Given day number g, calculate year, month, and day:

function d(g)
y = (10000*g + 14780)/3652425
ddd = g - (365*y + y/4 - y/100 + y/400)
if (ddd < 0) then
 y = y - 1
 ddd = g - (365*y + y/4 - y/100 + y/400)
 endif
mi = (100*ddd + 52)/3060
mm = (mi + 2)%12 + 1
y = y + (mi + 2)/12
dd = ddd - (mi*306 + 5)/10 + 1
return y, mm, dd

Applications.

Date differences.

The difference in days between two dates:
  g(y2,m2,d2) - g(y1,m1,d1)

Day offsets.

The date n days from y,m,d:

  d(g(y,m,d) + n)

Date legality.

To check if a date is on the calendar:

  if [y,m,d] = d(g(y,m,d))

Some implementations:

An POSIX shell program
An awk program
A C program source

Method.

A hastily-written description of the math and method.