dpointer
Monday, June 21, 2004
Doomsday
Given a date, how to know whether it's on Sunday, Monday, Tuesday, and so on? Enter Doomsday algorithm, from John Horton Conway. For a good explanation of this simple yet powerful algorithm, see http://rudy.ca/doomsday.html. Translating into quick-and-dirty C code, which is adopted from Richard Bowen's Date::DayOfWeek, it would be like the code fragment presented below. Note that isleapyear is only a helper function but could be useful nonetheless.
/* return non-zero if year is a leap year */
int isleapyear( int year )
{
if( !(year % 400 ) ) return 1;
if( !(year % 100 ) ) return 0;
if( !(year % 4 ) ) return 1;
return 0;
}
/* get day of the week (0=sunday) of any date */
/* doomsday algorithm: http://rudy.ca/doomsday.html */
int dayofweek( int day, int month, int year )
{
int doomsday, century, count;
int ddcentury[] = { 3, 2, 0, 5 };
int ddmonth[] = { 31, 28, 7, 4, 9, 6, 11, 8, 5, 10, 7, 12 };
century = year - (year % 100);
doomsday = ddcentury[ ( ( century - 1500 ) / 100 ) % 4 ];
doomsday += (int)( (year-century) / 12 );
doomsday += ( year - century ) % 12;
doomsday += (int)( ( ( year - century ) % 12 ) / 4 );
count = day - ddmonth[ month-1 ];
if( ( month < 3 ) && isleapyear( year ) ) count++;
count = ( doomsday + count ) % 7;
if( count < 0 ) count += 7;
return count;
}

