Electronic – How to calculate day of the week for RTC


I am using MCP7940 RTC from microchip it requires to enter the day of the week as part of updating RTC with date. So how should I calculate day of the week based on the date provided by the user ?

Best Answer

If you want to calculate the day-of-week yourself, here's a C implementation of part of a Perl module I wrote about 20 years ago. I like this algorithm because it doesn't require any looping or a table of month lengths. Note that ints are assumed to be 32 bits.

/* Returns the number of days to the start of the specified year, taking leap
 * years into account, but not the shift from the Julian calendar to the
 * Gregorian calendar. Instead, it is as though the Gregorian calendar is
 * extrapolated back in time to a hypothetical "year zero".
int leap (int year)
  return year*365 + (year/4) - (year/100) + (year/400);

/* Returns a number representing the number of days since March 1 in the
 * hypothetical year 0, not counting the change from the Julian calendar
 * to the Gregorian calendar that occured in the 16th century. This
 * algorithm is loosely based on a function known as "Zeller's Congruence".
 * This number MOD 7 gives the day of week, where 0 = Monday and 6 = Sunday.
int zeller (int year, int month, int day)
  year += ((month+9)/12) - 1;
  month = (month+9) % 12;
  return leap (year) + month*30 + ((6*month+5)/10) + day + 1;

/* Returns the day of week (1=Monday, 7=Sunday) for a given date.
int dow (int year, int month, int day)
  return (zeller (year, month, day) % 7) + 1;