//
// given month, day, year, returns day of week, eg. Monday = 0 etc.
// tested for 1901 to 2099 (seems to work from 1800 on too)
//
int weekday(int month, int day, int year)
{
int ix, tx, vx;
switch (month) {
case 2 :
case 6 : vx = 0; break;
case 8 : vx = 4; break;
case 10 : vx = 8; break;
case 9 :
case 12 : vx = 12; break;
case 3 :
case 11 : vx = 16; break;
case 1 :
case 5 : vx = 20; break;
case 4 :
case 7 : vx = 24; break;
}
if (year > 1900) // 1900 was not a leap year
year -= 1900;
ix = ((year - 21) % 28) + vx + (month > 2); // take care of February
tx = (ix + (ix / 4)) % 7 + day; // take care of leap year
return (tx % 7);
}
Now, I can obviously read what the code is doing, however I have no idea WHY it works. Any ideas?
On a completely unrelated thing, you can remove the
if (year > 1900) // 1900 was not a leap year
year -= 1900;
and change?
return (tx % 7);
to
return ((tx + 5) % 7);
and it works the same, I prefer this other solution to the one on the webpage.
Question
Argote
So, I came accross this code to calculate which day of the week a date is on, the source is here: http://www.daniweb.com/code/snippet65.html#
// // given month, day, year, returns day of week, eg. Monday = 0 etc. // tested for 1901 to 2099 (seems to work from 1800 on too) // int weekday(int month, int day, int year) { int ix, tx, vx; switch (month) { case 2 : case 6 : vx = 0; break; case 8 : vx = 4; break; case 10 : vx = 8; break; case 9 : case 12 : vx = 12; break; case 3 : case 11 : vx = 16; break; case 1 : case 5 : vx = 20; break; case 4 : case 7 : vx = 24; break; } if (year > 1900) // 1900 was not a leap year year -= 1900; ix = ((year - 21) % 28) + vx + (month > 2); // take care of February tx = (ix + (ix / 4)) % 7 + day; // take care of leap year return (tx % 7); }Now, I can obviously read what the code is doing, however I have no idea WHY it works. Any ideas?
On a completely unrelated thing, you can remove the
and change?
to
and it works the same, I prefer this other solution to the one on the webpage.
Link to comment
Share on other sites
5 answers to this question
Recommended Posts