mjavon
mjavon

Reputation: 237

Creating a date exactly one month in the past in SAS

I am trying to create two datetime variables in SAS 9.3. The first, "endDate" is the current datetime at the time the program is run. The second, "startDate" is exactly one month in the past.

My code is:

  %let endDate = %sysfunc(DATETIME() datetime.);
  %let startDate = %sysfunc(intnx('month', DATETIME(), -1) datetime.);

Based on any documentation I can find, I can't figure out what is wrong with it, but I am getting the following error message:

"ERROR: Expected close parenthesis after macro function invocation not found."

What am I doing wrong?

Some additional background: I want to use these two macro variables inside a proc sql statement so I can filter a table to data from within the past month at the run-time.

Thanks!

Upvotes: 1

Views: 1265

Answers (3)

user667489
user667489

Reputation: 9569

Four things:

  • You don't need the single quotes around string arguments when calling functions via %sysfunc
  • You need to use a %sysfunc for every individual data step function you want to call in the macro environment, which means you need to nest them in this case as you're calling one function inside another. This can get messy.
  • You need to increment your datetime by a datetime-month increment, not a month increment, so use dtmonth instead of month.
  • You need a comma between the function call and the format within %sysfunc

Putting it all together:

 %let endDate = %sysfunc(DATETIME(), datetime.);
 %let startDate = %sysfunc(intnx(dtmonth, %sysfunc(DATETIME()), -1), datetime.);

Upvotes: 2

Shenglin Chen
Shenglin Chen

Reputation: 4554

%let endDate = %sysfunc(DATETIME(), datetime21.);
%let startDate =%sysfunc(putn(%sysfunc(intnx(dtmonth, %sysfunc(DATETIME()), -1,same)),datetime21.));
%put  &enddate &startdate;

Upvotes: 0

Reeza
Reeza

Reputation: 21264

You have a couple of issues:

  1. %sysfunc() takes two parameters, the second one is optional, but it does need to be separated by a comma.
  2. Your use of DateTime() function in the intnx function also requires a %sysfunc()
  3. You have datetime variables so you need to use DTMONTH as your interval instead of month.
  4. You don't need quotes around literals in a macro call

     %let endDate = %sysfunc(DATETIME(), datetime.);
     %put &endDate;
    
     %let startDate = %sysfunc(intnx(dtmonth, %sysfunc(datetime()), -1), datetime.);
     %put &StartDate;
    

Upvotes: 4

Related Questions