Search code examples
sassas-macro

datetime comparison in if clause


I have the following code:

%if "&min_date"dt <= "02DEC2014:00:00:00"dt %then %do;
  /* some code */
%end

And it doesn't behave as I expect.

My min_date is inferior but the tested expression is evaluated to 0

%put &min_date; /* 31JAN1600:00:00:00 */
%put %eval("&min_date"dt <= "02DEC2014:00:00:00"dt); /* 0 */
%put %eval("31JAN1600:00:00:00"dt <= "02DEC2014:00:00:00"dt); /* 0 */

How do I make this work ?


Solution

  • As you have shown, %EVAL does not know about date-time literals, so it sees them as string values. Since %EVAL is called implicitly by an %IF statement. the %IF statement does a text comparison instead of numeric comparison.

    The good news is %SYSEVALF does know about date-time literals:

    %let min_date = 31JAN1600:00:00:00 ; 
    %put %sysevalf("&min_date"dt) ;   /*-11357884800*/
    %put %sysevalf("&min_date"dt <= "02DEC2014:00:00:00"dt);  /* 1 */
    %put %sysevalf("31JAN1600:00:00:00"dt <= "02DEC2014:00:00:00"dt); /* 1 */
    

    In a macro %IF:

    %macro test(min_date=) ;
      %if %sysevalf("&min_date"dt <= "02DEC2014:00:00:00"dt) %then %do;
        %put &min_date is less than or equal to "02DEC2014:00:00:00"dt ;
      %end ;
      %else %do ;
        %put &min_date is NOT less than or equal to "02DEC2014:00:00:00"dt ;
      %end ;
    %mend ;
    

    Which returns log like:

    124  %test(min_date=31JAN1600:00:00:00)
    31JAN1600:00:00:00 is less than or equal to "02DEC2014:00:00:00"dt
    125  %test(min_date=31JAN2015:00:00:00)
    31JAN2015:00:00:00 is NOT less than or equal to "02DEC2014:00:00:00"dt