This lesson details a variety of approaches we can use to convert a character variable (string) to a date variable in SAS.
Let's assume you run into a situation in which you need to convert character variable to SAS date format. This will typically happen when we upload raw data file type (TXT, EXCEL, or CSV) into SAS. The problem with having dates in character format is we can't do any calculations on them.
Sample Dataset to be used in this article
Convert Character Variable to SAS Date
We can convert the character variable (string) to numeric using INPUT function. We assign format of the date using MMDDYY10. format.
Output:
How to Change Character Variable to a Different Date Format
As you can see our original DOB variable is in Month-Date-Year format but stored as a character. If we need to change it to Date-Month-Year format stored as in SAS date format.
Always remember to put the way the original date is formatted in the INPUT function and the way you want it to appear in the FORMAT statement. If you were to put it in a different format in the INPUT function then SAS may return a missing value. For example, when trying to convert 04/20/1993 to DDMMYY10. format, SAS would read 20 as the month which is not possible.
Let's assume you run into a situation in which you need to convert character variable to SAS date format. This will typically happen when we upload raw data file type (TXT, EXCEL, or CSV) into SAS. The problem with having dates in character format is we can't do any calculations on them.
Sample Dataset to be used in this article
data intellectsage;
input DOB $20.;
cards;
05/15/1988
07/30/1990
04/20/1993
;
run;
Convert Character Variable to SAS Date
We can convert the character variable (string) to numeric using INPUT function. We assign format of the date using MMDDYY10. format.
Note: Please make sure that you create a new variable for conversion. If you use the same variable for conversion, the variable will retain its character format.data intellectsage_out;
set intellectsage;
DOB2 = input(strip(DOB),MMDDYY10.);
format DOB2 MMDDYY10.;
run;
Output:
How to Change Character Variable to a Different Date Format
As you can see our original DOB variable is in Month-Date-Year format but stored as a character. If we need to change it to Date-Month-Year format stored as in SAS date format.
data intellectsage_out;
set intellectsage;
DOB2 = input(strip(DOB), MMDDYY10.);
format DOB2 DDMMYY10.;
run;
Always remember to put the way the original date is formatted in the INPUT function and the way you want it to appear in the FORMAT statement. If you were to put it in a different format in the INPUT function then SAS may return a missing value. For example, when trying to convert 04/20/1993 to DDMMYY10. format, SAS would read 20 as the month which is not possible.