Calculating Day of the Week, Finally

Jul 25, 2012 By Dave Taylor  inHOW-TOsprogramming

As with many of the challenges we tackle, the latest project has sprawled across more articles 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, making this oodles easier. But it isn't, so we have to compensate.

Figuring the Day of the Week

Last time, 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 2011Su Mo Tu We Th Fr Sa1 2 3 4 5 6 78 9 10 11 12 13 1415 16 17 18 19 20 2122 23 24 25 26 27 2829 30 31

The actual return value of the function in this instance is 2, so 1

View the Original article

No comments:

Post a Comment

Thank You , For Immediate Assistance Plz Put Email Copy to Deviceporting@gmail.com