I have a SAS macro that always indicates the end of the past month. It currently has this value: 31AUG2022:23:59:59
I want a SAS macro that indicates this in a YYYYMM format. It should have this value: 202208
So far I've got this code:
%let PrevPeriod_yyyy = %sysfunc(year(%sysfunc(datepart(&PrevPeriod_dttm))));
%let PrevPeriod_m = %sysfunc(month(%sysfunc(datepart(&PrevPeriod_dttm))));
%let PrevPeriod_mm = %sysfunc(put(%sysfunc(input(&PrevPeriod_m, best2.)), z2.));
The idea with line 3 was to force the single-digit month to have 2 digits. So that'd it return 07 instead of 7 (while maintaining monthly values like 10/11/12).
If I can make line 3 work, then I can easily create 202207. Any idea what I'm doing wrong?
%SYSFUNC allows you to use a format.
%let wanted = %sysfunc(datepart(&PrevPeriod_dttm.),yymmn6.);
Since neither put nor input function can be used in %sysfunc, it may be easier to use the data step as follows.
%let PrevPeriod_dttm='31AUG2022:23:59:59'dt;
data _null_;
call symputx('PrevPeriod_yyyymm',put(datepart(&PrevPeriod_dttm),yymmn6.));
run;
%let PrevPeriod_mm = %sysfunc(putn(%sysfunc(inputn(&PrevPeriod_m., best2.)), z2.));
%SYSFUNC allows you to use a format.
%let wanted = %sysfunc(datepart(&PrevPeriod_dttm.),yymmn6.);
If I can make line 3 work, then I can easily create 202207. Any idea what I'm doing wrong?
In addition to the correct answers already given, please understand that pulling apart text strings and then combining them is not the way to obtain calendar/date/month/year strings such as 202207. SAS has already done the hard work so you don't have to do this. Use the built in formats and informats to handle creation of calendar information strings. If you find yourself trying to pull apart calendar strings and somehow put them back together, then that is what you are doing wrong.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.