Search code examples
sas

Convert yyyymm into sas date9 and split


I have dates like "202407". How can I convert them into Sas date9. format to have "JUL2024"? Is there also a way to separate into two new variables the month "7" and the year "2024"?

Thank you in advance.

Best


Solution

  • If you have a character variable you can use the YYMMN informat to convert it to a date value. You could then use the MONYY format to display it like JUL2024.

    875   data test;
    876    x=input('202407',yymmn6.);
    877    put x=comma. x=date9. x=monyy7.;
    878   run;
    
    x=23,558 x=01JUL2024 x=JUL2024
    

    You could also use the MONTH() and YEAR() functions to calculate the year number and month number.

    So if your existing dataset is named HAVE and the existing variable is named DATE_CHAR then you could use code like this to make a new variable named DATE_NUM.

     data want;
        set have;
        date_num = input(date_char,yymmn6.);
        year = year(date_num);
        month = month(date_num);
        format date_num monyy7. month z2. ;
     run;
    

    If you want the YEAR and MONTH as strings then you could just use SUBSTR() function to pull apart your character variable.

     data want;
       set have;
       year_char = substr(date_char,1,4);
       month_char = substr(date_char,5,2);
     run;
    

    If the existing variable is already a DATE valued variable but has the YYMMN6. format attached to it so it prints in that yyyymm style then you can skip the INPUT() function since you already have a date value. You can just change what format is attached to have it print in MONYYYY style instead YYYYMM style.

     data want;
        set have;
        year = year(date_num);
        month = month(date_num);
        format date_num monyy7. month z2. ;
     run;
    

    If the existing variable is just a regular number with values like YYY,YMM (where the ones and tens place represent the month number) then first convert it to 6 digit string using the PUT() function with the 6. or Z6. format. Then apply the logic above for converting the 6 digit string back into a data value.

    data want;
       set have;
       date_char = put(date_num,Z6.);
       date_num = input(date_char,yymmn6.);
       year = year(date_num);
       month = month(date_num);
       format date_num monyy7.;
    run;
    

    Or you could use arithmetic to get the year and month out of the number. Then use the numeric year and month to generate an actual date value.

    data want;
       set have;
       year = int(date_num/100);
       month = mod(date_num,100);
       date_num = mdy(month,1,year);
       format date_num monyy7. month z2. ;
    run;