Elena
Elena

Reputation: 19

Sas changing of date format

I have three columns with date formatted differently in SAS:

  1. 12 june 2017 00:15 - full date
  2. 2016 - only year
  3. 12 - only month

I Need to change the format of date and subtract after the dates to get results in the number of months.

for instance, "12 June 2017 00:15" - December 2016 = 7

how to do it?

Upvotes: 0

Views: 449

Answers (3)

Tom
Tom

Reputation: 51621

Assuming that you have three numeric variables and the first one contains valid SAS datetime values you should first convert both to valid SAS date values. You can then use the INTCK() function to count months.

 nmonths = intck('month',datepart(VAR1),mdy(VAR3,1,VAR2));

Upvotes: 0

Sashole
Sashole

Reputation: 1

  1. Convert the "full date" field to a SAS date value.
  2. Convert the combo of year and month to a SAS date value, too.
  3. Use the INTCK function to find the difference in months.

For example:

data dates ;
input dt $18. yy mm ;
mm_diff = intck ("mon", input (cats (yy, mm), yymmn6.), input (dt, anydtdte12.)) ; put mm_diff= ;
cards ;
12 june 2017 00:15 2016 12
11 june 2018 00:15 2017 3
;
run ;

The log will print:

mm_diff=6 mm_diff=15

As a side note, the statement "there isn't a ready-made SAS date informat that will correctly handle your full date field" made elsewhere in this thread is incorrect. As the program snippet above shows, the ANYDTDTEw. informat handles it with aplomb. It's just incumbent upon the programmer to supply a sufficient informat width W. Above, it is selected as W=12. If you're reluctant to guess and/or count, just use ANYDTDTE32.

Regards, Paul Dorfman

Upvotes: 0

user667489
user667489

Reputation: 9569

As you have probably already found, there isn't a ready-made SAS date informat that will correctly handle your full date field, so you'll need to write a bit of custom logic to convert it before doing your calculation. date9. is the closest matching format I could find:

data example;
fulldate = '12 june 2017 00:15';
year = 2016;
month = 12;
/* Convert string to date9 format and input */
fulldate_num = input(
  cats(
    scan(fulldate,1),
    substr(scan(fulldate,2,' '),1,3),
    scan(fulldate,3)
  ), date9.
);
/* Calculate difference in months */
monthdiff = intck('month', mdy(month,1,year), fulldate_num);
run;

Upvotes: 1

Related Questions