DATA Step, Macro, Functions and more

Convert character date to YYYYMMDD date field

Accepted Solution Solved
Reply
Regular Contributor
Posts: 218
Accepted Solution

Convert character date to YYYYMMDD date field

Hi All,

My date field (Imported from Excel) written like 2/30/2015 and have $10. format. Can someone help me to convert it to 20150230 format please. Thanks,

 


Accepted Solutions
Solution
‎03-22-2016 02:05 PM
Trusted Advisor
Posts: 1,117

Re: Convert character date to YYYYMMDD date field

Hi @mlogan,

 

I would create SAS date values from those character dates:

data _null_;
length c $10;
c='3/30/2015';
d=input(c,mmddyy10.);
format d yymmddn8.;
put d;
run;

If you need a character string in YYYYMMDD format you can apply the PUT function to the SAS date value:

dc=put(input(c,mmddyy10.),yymmddn8.);

 

For invalid dates the conversion will fail, though. :-)

View solution in original post


All Replies
Solution
‎03-22-2016 02:05 PM
Trusted Advisor
Posts: 1,117

Re: Convert character date to YYYYMMDD date field

Hi @mlogan,

 

I would create SAS date values from those character dates:

data _null_;
length c $10;
c='3/30/2015';
d=input(c,mmddyy10.);
format d yymmddn8.;
put d;
run;

If you need a character string in YYYYMMDD format you can apply the PUT function to the SAS date value:

dc=put(input(c,mmddyy10.),yymmddn8.);

 

For invalid dates the conversion will fail, though. :-)

Regular Contributor
Posts: 218

Re: Convert character date to YYYYMMDD date field

Posted in reply to FreelanceReinhard
Thanks Reinhard.
Regular Contributor
Posts: 218

Re: Convert character date to YYYYMMDD date field

Posted in reply to FreelanceReinhard
Hi Reinhard,
Would you please tell me what I have to do if I want to convert the existing column to YYMMDDN8. format without making a new column. Here in your example converting column 'c' without making a new column 'd'.
Trusted Advisor
Posts: 1,117

Re: Convert character date to YYYYMMDD date field

You could drop the old (character) variable and rename the new (numeric) one:

data have;
length c $10;
c='3/30/2015';
run;

data want;
set have;
d=input(c,mmddyy10.);
format d yymmddn8.;
drop c;
rename d=c;
run;

If your goal is a character variable (such as DC in my previous post), you could overwrite the existing value directly, because no type conversion would occur:

data want;
set have;
c=put(input(c,mmddyy10.),yymmddn8.);
run;

However, this would leave the length of the variable at 10, although 8 would be sufficient. To avoid this, you could define a new variable with length 8 and then drop and rename as shown above.

 

Regular Contributor
Posts: 218

Re: Convert character date to YYYYMMDD date field

Posted in reply to FreelanceReinhard
Thanks Reinhard, I did not know this drop trick. Very helpful.
☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 5 replies
  • 3248 views
  • 2 likes
  • 2 in conversation