View Single Post
  #10   Report Post  
Harlan Grove
 
Posts: n/a
Default

Lewis Clark wrote...
....
Here's what I don't understand: Since the last day of the previous month
can be any day of the week, I can't figure out how you know in advance what
correction to make with the WkDay term.


WEEKDAY(x,3) returns numbers between 0 and 6 no matter what x is (for x
0). Since y-DAY(y)+14 is the 14th day of the month, it's the last day in the month that could be the 2nd particular weekday in the month. In order to get the particular weekday desired, it may be necessary to back up from the 14th day of the month.


At that point it's a simple one-to-one relation. Here's a mapping of
the offsets needed by weekday of the 14th of the month and weekday
desired.

WkDay Desired
wkDay of 14th Mo Tu We Th Fr Sa Su
Mo 0 6 5 4 3 2 1
Tu 1 0 6 5 4 3 2
We 2 1 0 6 5 4 3
Th 3 2 1 0 6 5 4
Fr 4 3 2 1 0 6 5
Sa 5 4 3 2 1 0 6
Su 6 5 4 3 2 1 0

This shows a regular pattern. The key here is realizing that the offset
would be the same no matter which day of the week the 14th day of the
month was, so it's only necessary to figure out what offset would be
needed when Monday were the 14th day of the month. When the 14th is
Monday and the weekday desired is Monday, no offset needed, so add or
subtract 0 or 7. If Tuesday were desired, add 6 or subtract 1. If
Wednesday were desired, add 5 or subtract 2. Etc.

I chose to use additive offsets because they won't generate date values
< 0 when y is any valid date from 1-Jan-1900 through 24-Dec-9999.
Subtracing offsets could cause problems with dates before 7-Jan-1900.
Since it's slightly more likely people these days would be using dates
near the turn of the 20th century rather than near the end of the 99th
century, additive offsets would be slightly safer.