Computing The Day of the Week (DoW) Any Number of Days (±N) in Relative Past or Future From Any Given Known Starting Point
Suppose we know a certain date is a Thursday (DoWa = 4) and we wish to find (DoWb = ?) for a date N days before or after that date. This algorithm handles that type of problem and applies to both the Julian and Gregorian calendars.
Given any known starting weekday (
DoWa), the following algorithm will compute the day of the week (
DoWb) any number of days (±
N) in the relative past or future from that starting point.
Algorithm 7:
Starting on any weekday (DoWa), compute the weekday (DoWb) ±N days from that day.
if N < 0 then SignVal = -1 else SignVal = 1
DoWb = (DoWa + 7 + SignVal*(abs(N) mod 7)) mod 7
or
SignVal = (N < 0)? -1:1
DoWb = (DoWa + 7 + SignVal*(abs(N) mod 7)) mod 7
or
DoWb = (DoWa + 7 + ((N < 0)? -1:1)*(abs(N) mod 7)) mod 7
In PHP, it can be written as
$DoWb = ($DoWa + 7 + (($N < 0)? -1:1)*(abs($N) % 7)) % 7;
DoW Indices:
0=Sun,
1=Mon,
2=Tue,
3=Wed,
4=Thu,
5=Fri and
6=Sat
EXAMPLE 1:
Starting on any Tuesday (DoWa=2), what would be the day of the week (DoWb) exactly 2013 days in the future?
DoWa = 2 (Tuesday)
N = 2013
The algorithm gives:
SignVal = (2013 < 0)? -1:1 = 1
DoWb = (2 + 7 + 1*(abs(2013) mod 7)) mod 7 = 13 mod 7 = 6 (Saturday)
So, starting on any Tuesday, exactly 2013 days later it will be a Saturday, even though we may not know the actual calendar date itself.
EXAMPLE 2:
Starting on any Friday (DoWa=5), what would be the day of the week (DoWb) exactly 5717 days in the past?
DoWa = 5 (Friday)
N = -5717
The algorithm gives:
SignVal = -1
DoWb = (5 + 7 + -1*(abs(-5717) mod 7)) mod 7 = 7 mod 7 = 0 (Sunday)
So, starting on any Friday, exactly 5717 days earlier would be a Sunday.
|