cph_sto
cph_sto

Reputation: 7585

SAS: Creating a macro variable containing all months between two dates

I have a macro variable in date yyyymm format, where yyyy is year like 2020 and mm is month like 02, as shown below:

%let m=202002;

How can I construct a macro variable m_new having as many months in the past as we specify? For eg; if num is 5, we get a macro variable having that many months from the past including the one itself. Something like

%put &m_new.
    202002 202001 201912 201911 201910

Upvotes: 2

Views: 1693

Answers (2)

Tom
Tom

Reputation: 51566

You could do it with a macro (or just a %DO loop if you are already inside a macro).

The issue is you need to convert YYYYMM values into an actual date. Then you can use INTNX() to generate the new dates and format them with YYMMN6. format to generate new YYYMM strings.

%macro months(start,number);
%local i date ;
%let date=%sysfunc(inputn(&start.01,yymmdd8));
%do i=0 %to %eval(&number-1); %sysfunc(intnx(month,&date,-&i),yymmn6)%end;
%mend ;

%put %months(start=202002,number=5);

Upvotes: 2

PeterClemmensen
PeterClemmensen

Reputation: 4937

Here is one way

%let m=202002;
%let n=5;

data _null_;
   length dt_c $ 500;
   dt = input ("&m.", yymmn6.);
   dt_c = put(dt, yymmn6.);
   do i = 1 to &n.-1;
      dt_c = catx(' ', dt_c, put(intnx('month', dt, -i), yymmn6.));
   end;
   call symputx('m_new', dt_c);
run;

%put &m_new.;

Result:

202002 202001 201912 201911 201910

Upvotes: 2

Related Questions