|
How to
Calculate the Day of the Week for Any Date.
This example is here for demonstration purposes, not for you to
figure out the code.
Days
of the Week
var daysofweek = new Array('Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday');
Calculating
the day of the week
The following was taken from The
Calendar FAQ.
To calculate the day on which a particular date falls, the
following algorithm may be used (the divisions are integer divisions,
in which the remainders are discarded):
a = (14 - month) / 12
y = year - a
m = month + 12 * a - 2
d = (day + y + y / 4 - y / 100 + y / 400 + (31 * m / 12) % 7
The value of d is 0 for a Sunday, 1 for a Monday, 2 for a Tuesday,
etc.
This can be converted into the following simple script, where
Math.floor converts floating point numbers to integers:
function DayOfWeek(day, month,
year) {
var a = Math.floor((14 - month) / 12);
var y = year - a;
var m = month + 12 * a - 2;
var d = (day + y + Math.floor(y / 4) - Math.floor(y /
100) +
Math.floor(y / 400) + Math.floor((31 * m) / 12)) % 7;
return d;
}
Converting
it to a named day
To test the function out, we'll find the day of the week that I was
born on, by using the daysofweek[]
array to display the day name:
document.write(daysofweek[DayOfWeek(4,
1, 1965) + 1]);
Which when run produces the following: |