Thursday, May 30, 2013

SAS: Get file creation date

I needed to know when a SAS file had been created, because I did not want a nightly process to replace the file if it had been manually created that same day.  This code will get the creation date of a file (any file, not just a SAS file) and save it as a SAS date in a macro variable.

I got burned with this, not knowing that Windows and Linus would return the date in completely different formats!

     Windows returned:  Wed May 29 22:02:21 2013
     Linus returned:  29May2013:22:02:21

Hence the use of the substr function below.

* What is the creation date of the existing file? ;
* See http://support.sas.com/kb/38/267.html ;
data _null_;
rc = filename("myfile", "full_path_and_filename_here.ext");
put rc=;
fid = fopen("myfile");
infonum = foptnum(fid);
do i = 1 to infonum;
    infoname = foptname(fid, i);
    infoval = finfo(fid, infoname);
    put infoname= infoval=;
    if (infoname = "Last Modified") then do;
        if ("&SYSSCPL" = "Linux") then do;        * Wed May 29 22:02:21 2013 ;
            year = substr(infoval, 21, 4);        * 2013 ;
            month = substr(infoval, 5, 3);        * May ;
            day = substr(infoval, 9, 2);          * 29 ;
            time = substr(infoval, 12, 8);        * 22:02:21 ;
            together = trim(day) || trim(month) || trim(year) || ":" || trim(time);  

            * Now it is 29May2013:22:02:21, same as Windows now ;
            put together=;
            createDateTime = input(together, anydtdtm20.);
            createDate = datepart(createDateTime);
        end;
        else do;
            createDateTime = input(infoval, anydtdtm20.);
            createDate = datepart(createDateTime);
        end;
        put createDate=;
        call symput("CREATE_DATE", trim(left(createDate)));
    end;
end;
close = fclose(fid);
run;

%put *** CREATE_DATE=&CREATE_DATE;