# Finding the day of the week

1. Jul 4, 2010

### magnifik

i am trying to find when the first day of the week is for a given year and month. this formula gives the day of the first day of the year:

(([y-1]*365+[y-1]/4-[y-1]/100+[y-1]/400)+1)%7

if it equals 0, it starts on sunday. 1 means monday, 2 means tuesday, and so on ending with 6 for saturday. the problem is i am trying to figure out how this formula can help me find the beginning of all the months, not just january. any help would be appreciated.

2. Jul 4, 2010

### Staff: Mentor

If you know what day of the week January 1 falls on for a given year, it's not too difficult to figure out what day of the week any month falls on. The sticky part is whether the given year is a leap year, which figures into how many days are in February.

It might be helpful to have an enumerated type with the days of the week, letting Sunday = 0, Monday = 1, ..., Saturday = 6. If Jan 1 falls on Sunday, the last day of January is the 31st, and 31 % 7 = 3. This means that Feb starts on the day whose enumeration value is 3, or Wednesday. If this seems like we're finding the day of the week that the last month falls on, it's because there's a mismatch between how days of the month are numbered (starting from 1) and how days in the enumeration are numbered (starting from 0).

Similarly, if Jan 1 falls on, say, a Tuesday (enumeration value 2), you have February starting on day (2 + 31 %7) = day 5, or Friday.

One final example: If if Jan 1 falls on, say, a Friday (enumeration value 5), February starts on day (5 + 31 % 7) = day(8) = day(1), or Monday. The calculation is really (5 + 31%7)%7. This is the main reason for have the enumeration start from 0 for Sunday; it make the calculations a lot simpler.

It gets tricky finding the day of the week that Mar 1 falls on, since February can have 28 days (non-leap year) or 29 days (leap year). If the year is a non-leap year, Mar 1 falls on the same day as Feb 1. If it's a leap year, Mar 1 occurs one day later. For example, if Feb 1 is on a Saturday (day 6), Mar 1 will be on Saturday in a non-leap year, and on day (6 + 1)%7 = day 0 or Sunday in a leap year.

Once you know what day of the week is for Mar 1, you can find what day of the week is for Apr 1, May 1, etc., using logic similar to the preceding.

As for when a leap year occurs, the year has to be evenly divisible by 4, but not evenly divisible by 100 except if they happen to be evenly divisible by 400. So for example, 1996 was a leap year (evenly divisible by 4), and 2000 was a leap year (evenly divisible by 400), but 1900 was not a leap year (divisible by 100 but not 400)

3. Jul 4, 2010

thanks