bstockton
bstockton

Reputation: 577

Number of months between two dates SAS

I Have bunch of data points data that looks like this. Sample:

        Date_1              Date_2
   10FEB2010:00:00:00      02/07/08
   10FEB2010:00:00:00      03/10/08
   10FEB2010:00:00:00      04/07/08
   24MAY2010:00:00:00      05/09/08      
   24MAY2010:00:00:00      06/11/08      
   24MAY2010:00:00:00      07/11/08

I would like to index both dates from the beginning of the month, then get the number of months in between in a new column called "month_from." I would like to add the new column "month_from" to my sample data set so it looks like this:

       Date_1              Date_2      month_from
   10FEB2010:00:00:00      02/07/08       -24
   10FEB2010:00:00:00      03/10/08       -23  
   10FEB2010:00:00:00      04/07/08       -22
   24MAY2010:00:00:00      05/09/08       -24
   24MAY2010:00:00:00      06/11/08       -23
   24MAY2010:00:00:00      07/11/08       -22

my initial attempt is:

 month_from=intck('month.1','Date_1'd,'Date_2'd);

Am I using the correct function?

How about adding variable "month_from" to sample data set?

Upvotes: 0

Views: 20006

Answers (1)

Jay Corbett
Jay Corbett

Reputation: 28391

This seems to do what you are looking for...couldn't tell if you needed to convert date_1 and date_2 from character to numeric(dates)..so I included that code also.

(also didn't bother to test if the INTCK date variables need to be at the 1st of the month to give the correct results)

data have;
 length date_1 $18 date_2 $8;
 infile datalines delimiter=','; 
 input date_1 $ date_2 $;

 datalines;
10FEB2010:00:00:00,02/07/08
10FEB2010:00:00:00,03/10/08
10FEB2010:00:00:00,04/07/08
24MAY2010:00:00:00,05/09/08
24MAY2010:00:00:00,06/11/08
24MAY2010:00:00:00,07/11/08
;

data want (drop=date_1 date_2 dt);
 set have;
 dt=input(date_1,datetime.);
 date1=datepart(dt);
 date2=input(date_2,mmddyy10.);

 month_from=intck('month',intnx('month',date1,0,'b'),intnx('month',date2,0,'b'));
 format date1 date2 mmddyy10.;
run;

Upvotes: 2

Related Questions