简体   繁体   中英

Date calculations in SAS

I want to add 1 day to an arbitrary SAS date. I have the following code that works but I wonder wether there is built-in support for date calculations like this:

proc fcmp outlib=whatever;  
function lastDayInYear(d);  
    if datdif(d,mdy(12,31,year(d)),'ACT/365')=0 then return(1); else return(0);  
endsub;  

function advanceDate(d);
    if d=. then return(.);
    if lastDayInYear(d) then
        return(mdy(1,1,year(d)+1));
    else
        return(datejul(juldate7(d)+1));
endsub;
quit;

Dates are just numbers, so to advance the day by one, you just, um, add 1.

Where did you find that code? Talk about using a sledgehammer to crack a nut...

Itzy is right... just add 1. If you want to do more advanced date calculations you can use the intnx() and intck() functions.

eg

data _null_;
  tomorrow            = date() + 1;
  same_day_next_month = intnx('month',date(),1,'same');
  first_day_next_week = intnx('week' ,date(),1,'beginning');
  last_day_of_year    = intnx('year' ,date(),0,'end');

  put _all_; 
run;

In SAS, there's no DATE or DATETIME data type, such values are stored as generic Numeric data type, where for date: the number stored represents number of days between date represented and January 1st 1960. For datetime it's similar, only number of seconds is stored. You'll see this in code below. Human readable date, time and datetime representation is achieved via SAS date/time formats. For further explanation just do a search on SAS dates on web and documentation.

Back to you're question: to add one day to a value representing DATE, just do a mathematical addition: +1.

data _null_;
    length mydate mydatetime 8;
    mydate='1jan1960'd;
    mydatetime='1jan1960:00:00:00'dt;
    nextdate = mydate + 1;
    nextminute = mydatetime + 60;
    put mydate 8. +4 mydate yymmdds10.;
    put nextdate 8. +4 nextdate yymmdds10.;
    put mydatetime 12. +4 mydatetime datetime.;
    put nextminute 12. +4 nextminute datetime.;
run;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM