I was looking at some SAS documentation when I saw a Base SAS function that I never knew existed. The NWKDOM function returns the date for the nth occurrence of a weekday for the specified month and year. I surely could have used that function last spring when I blogged about how to compute the onset and end of daylight saving time (DST) in SAS!
As any handyman will tell you, having the right tool makes a job so much easier. Instead of nine complicated lines of SAS DATA step code, my new algorithm consists of two calls to the NWKDOM function! In the US, DST ends on the first Sunday in November. Here's all you need to do to figure out that date in 2012: nwkdom(1, 1, 11, 2012). The first argument specifies the week (first=1). The second argument specifies the day of the week as a number 1–7 (Sunday=1). The third argument specifies the month as a number 1–12 (November=11). The last argument is the year.
Therefore, the following DATA step code computes the beginning and end of DST for several years:
/* compute the beginning and end of daylight saving time for several years */ data DST; format dst_beg dst_end DATE5.; do year=2012 to 2022; dst_beg = nwkdom(2, 1, 3, year);/*DST begins 2nd Sun in March */ dst_end = nwkdom(1, 1,11, year);/*DST ends 1st Sun in Nov */ output; end; run; proc print noobs; var year dst_beg dst_end; run; |
With the right tools, every task is easier.
2 Comments
Using this approach to calculate the start and end of British Summer Time illustrates another feature. BST starts on the last Sunday of March and ends on the last Sunday in October. If you pass a 5 and then a 1 to nwkdom as the first two arguments; it will find the last Sundays. Here is the code:
/* compute the beginning and end of British Summer Time for several years */
data BST;
format bst_beg bst_end DATE5.;
do year=2012 to 2022;
bst_beg = nwkdom(5, 1, 3, year);/*BST begins last Sun in March */
bst_end = nwkdom(5, 1,10, year);/*BST ends last Sun in Oct */
output;
end;
run;
proc print noobs;
var year bst_beg bst_end;
run;
What about when the government changes DST again? The algorithm should be flexible for that possibility, to avoid the Y2K-like disaster of hard-coded DST settings in operating systems.