DATA Step, Macro, Functions and more

Convert Text to Date format

Reply
N/A
Posts: 0

Convert Text to Date format

In SAS 9, I have a table that has a text field that holds information that is a date in YYYYMMDD format. I need to convert this data to a date format as I need to do comparisons on this field.

Some samples from the field would be:

20081002
20070417
20080101

The field these are stored in is a text field. How can I make this data workable if I need to compare it to another date, say finding all data that is within the last year.

Thanx.
Andy
SAS Super FREQ
Posts: 8,743

Re: Convert Text to Date format

Hi:

You might want to investigate the INPUT function. For example, if your text field was called CHARSTR, then you could create a numeric variable from the character field by using the INPUT statement:
[pre]
newdate = input(charstr,yymmdd8.);
[/pre]

In this instance, (inside a DATA step program), the new variable NEWDATE would be numeric, would be internally stored as the number of days since Jan 1, 1960, and could be formatted with any of the SAS date formats.

You could then do comparisons or test conditions using NEWDATE like this:
[pre]
if year(newdate) = 2007 . . .
or
if newdate lt '01Jan2008'd . . .
or
if year(newdate - 180) = 2007 . . .
[/pre]

cynthia

ps...there have been a lot of previous forum postings on the conversion of character dates to SAS date values. A search of the forum, might get you some more code examples.
Ask a Question
Discussion stats
  • 1 reply
  • 145 views
  • 0 likes
  • 2 in conversation