How to convert String to Date value in SAS?
Matthew Barrera
I want to convert a String to Date in SAS, I tried:
data _null_; monyy = '05May2013'; date = input(substr(strip(monyy),1,9),yymmdd.);; put date=date9.; run;But it did not work. Can this be done?
7 Answers
Formats like
date9. or
mmddyy10. are not valid for input command while converting text to a sas date. You can use
Date = input( cdate , ANYDTDTE11.);or
Date = input( cdate , ANYDTDTE10.); for conversion.
2You don't need substr or strip.
input(monyy,date9.); As stated above, the simple answer is:
date = input(monyy,date9.);with the addition of:
put date=yymmdd.;The reason why this works, and what you did doesn't, is because of a common misunderstanding in SAS. DATE9. is an INFORMAT. In an INPUT statement, it provides the SAS interpreter with a set of translation commands it can send to the compiler to turn your text into the right numbers, which will then look like a date once the right FORMAT is applied. FORMATs are just visible representations of numbers (or characters). So by using YYMMDD., you confused the INPUT function by handing it a FORMAT instead of an INFORMAT, and probably got a helpful error that said:
Invalid argument to INPUT function at line... etc...Which told you absolutely nothing about what to do next.
In summary, to represent your character date as a YYMMDD. In SAS you need to:
- change the INFORMAT -
date = input(monyy,date9.); - apply the FORMAT -
put date=YYMMDD10.;
Try
data _null_; monyy = '05May2013'; date = input(substr(strip(monyy),1,9),date9.); put date=date9.; run; input(char_val, date9.);
You can consider to convert it to word format using input(char_val, worddate.)
You can get a lot in this page
This code helps:
data final; set final;
first_date = INPUT(compress(char_date),date9.); format first_date date9.;
run;I personally have tried it on SAS
input(char_val,current_date_format);You can specify any date format at display time, like set char_val=date9.;