Calculating Day
of the Week, Finally
DAVE TAYLOR
Dave wraps up the script and leaves us with the problem of Leap Year.
As with many of the challenges we
tackle in this column, the latest project has
sprawled across more issues than I ever
expected when I first received the query
from a reader. The question seems reasonably simple: given a month, day number
and day of the week, calculate the most
recent year that matches those criteria.
There are some obscure and complex
formulas for doing just this, but instead, I
decided it’d be interesting basically to loop
backward from the current year for the
month in question, parsing and analyzing
the output of the handy cal program.
The real challenge has been that the
cal program never really was designed
to produce easily parsed output, so
figuring out the day of the week (DOW,
as we’ve been abbreviating it) involves
basically counting the number of leading
spaces or otherwise compensating for
an average month where the first day
starts mid-week, not neatly on Sunday.
An algorithmic-friendly version of cal
would have output where days prior to
the first day of the month would be output optionally as zeros or underscores,
40 | SEPTEMBER 2011 WWW.LINUXJOURNAL.COM
making this oodles easier. But it isn’t, so
we have to compensate.
Figuring the Day of the Week
Last month, we wrapped up with a
shell function that expected the day,
month and year as arguments and
returned the day of the week of that
particular date in that month on that
year. In other words, 16 May, 2011,
occurs on a Monday:
May 2011 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
The actual return value of the function in this instance is 2, so 1 = Sunday,
2 = Monday, and so on.
Given the desired day of the week that
the user specifies and a simple way to
decrement the year until we hit a match
coupled with the function already shown,