Skip to content

Instantly share code, notes, and snippets.

@statgeek
Last active March 3, 2020 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save statgeek/9606118 to your computer and use it in GitHub Desktop.
Save statgeek/9606118 to your computer and use it in GitHub Desktop.
SAS - Date Dimension
/*This creates a date dimension table that can be used for
looking up dates. This is less relevant as SAS has allowed
for custom intervals, but a quick solution often.*/
%MACRO DATE_DIMENSION(startdate=, enddate=, outfil=);
data &outfil;
retain number_workdays;
do _n_ = &startdate to &enddate;
date_id + 1;
date = _n_;
format date mmddyy10.;
month = month(date);
calendar_month = year(date)*100+month(date);
day = day(date);
year = year(date);
quarter = mod(qtr(date)+2,4)+1;
length fiscal_year $10.;
if quarter in (2, 3,4) then fiscal_year=compress(cat(year ,"/",year+1));
else if quarter=1 then fiscal_year=compress(cat(year-1,"/",year));
format fiscal_year $10.;
length fiscal_year $10.;
dayofweek=weekday(date);
if dayofweek >= 2 and dayofweek<=6 then workday=1; else workday=0;
if date in ('01JAN2013'd,'18FEB2013'd,'29Mar2013'd '01APR2013'd,'22MAY2013'd,
'01JUL2013'd,'05AUG2013'd,'02SEP2013'd,'14OCT2013'd,'11NOV2013'd,
'25DEC2013'd,'26DEC2013'd, '27Dec2013'd, '01Jan2014'd, '17Jan2014'd, '18Apr2014'd,
'21Apr2014'd, '19May2014'd, '01Jul2014'd, '04Aug2014'd, '01Sep2014'd, '13Oct2014'd,
'11Nov2014'd, '24Dec2014'd, '25Dec2014'd, '26Dec2014'd, '01Jan2015'd ) then isholiday=1; else isholiday=0;
if isholiday then workday=0;
if day=1 and month=1 then number_workdays=0;
number_workdays+workday;
output;
end;
run;
%MEND DATE_DIMENSION;
%date_dimension(startdate='01jan2013'd, enddate='31Dec2013'd,outfil=date_dimension)
*get previous work day;
%let test_date="01Feb2013"d;
proc sql;
select max(date) format=date9. into :prev_work_day from
date_dimension where workday=1 and date < &test_date;
quit;
%put &prev_work_day;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment