user1626092
user1626092

Reputation: 499

Date formatting a character variable in SAS

I have a character variable with a the value like this:

Aug 1, 2015

I want to have this date value in a date9. and a DDMMYYD10. format.

This is what I have tried:

month=upcase(substr(startdato,1,3));
day=0!!substr(startdato,5,1);
year=substr(startdato, 8,4);
startdato_a=trim(day)!!trim(month)!!trim(year);

FORMAT  Startdato2 date9.;
format startdato3 DDMMYYD10.;

Startdato2 = INPUT(startdato_a,date9.);
Startdato3 = INPUT(startdato_a,date9.);

I get this output:

month=AUG
day=01
year=2015
startdato_a=01AUG2015
startdato2=.
startdato3=.

Why don't I get values in startdato2 and startdato3?

Upvotes: 0

Views: 601

Answers (2)

Tom
Tom

Reputation: 51566

Output your character variables using the $QUOTE. function is a handy way to see leading blanks. Doing this you can see the what is causing the trouble with the INPUT() function.

startdato="Aug 1, 2015"
month="AUG"
day="           01"
year="2015"
startdato_a="           01AUG2015"

The cause of this is including a numeric constant when generating that character string.

day=0!!substr(startdato,5,1);

SAS had to convert the 0 into a string so it used best12. format which is why there are 11 leading blanks in the value of DAY. You could have use a string literal instead.

day='0'!!substr(startdato,5,1);

Which would yield better results.

startdato="Aug 1, 2015"
month="AUG"
day="01"
year="2015"
startdato_a="01AUG2015"
Startdato2=01AUG2015
startdato3=01-08-2015

Upvotes: 0

user667489
user667489

Reputation: 9569

You are getting missing values due to leading / trailing whitespace in startdato_a, which prevents the informat from working properly. If you do input(strip(startdato_a),date9.) instead, it works as expected.

However, there is a much simpler way of doing this:

data want;
textdate = 'Aug 1, 2015';
date = input(textdate,anydtdte11.);
format date date9.;
run;

Upvotes: 1

Related Questions