You can use the INTCK function in SAS to quickly calculate the difference between two dates in SAS.
This function uses the following basic syntax:
INTCK(interval, start date, end data, method)
where:
- interval: Interval to calculate (day, week, month, quarter, year, etc.)
- start date: The start date
- end date: The end date
- method: Count intervals using a discrete or continuous method
The following example shows how to use this function in practice.
Example: Using INTCK Function to Calculate Difference Between Dates in SAS
Suppose we have the following dataset in SAS that contains two date variables:
/*create dataset*/
data original_data;
format start_date end_date date9.;
input start_date :date9. end_date :date9.;
datalines;
01JAN2022 09JAN2022
01FEB2022 22FEB2022
14MAR2022 04APR2022
01MAY2022 14AUG2023
06AUG2022 10NOV2024
;
run;
/*view dataset*/
proc print data=original_data;
We can use the following code to calculate the difference between the values in the start_date and end_date variables in days, weeks, months, quarters and years:
/*create new dataset*/
data new_data;
set original_data;
days_diff = intck('day', start_date, end_date);
weeks_diff = intck('weeks', start_date, end_date);
months_diff = intck('months', start_date, end_date);
qtr_diff = intck('qtr', start_date, end_date);
years_diff = intck('years', start_date, end_date);
run;
/*view new dataset*/
proc print data=new_data;
The five new variables show the difference between start_date and end_date in days, weeks, months, quarters, and years.
Note that we can use the ‘c‘ argument in the INTCK function to only calculate the difference in complete days, weeks, months, quarters and years:
/*create new dataset*/
data new_data;
set original_data;
days_diff = intck('day', start_date, end_date, 'c');
weeks_diff = intck('weeks', start_date, end_date, 'c');
months_diff = intck('months', start_date, end_date, 'c');
qtr_diff = intck('qtr', start_date, end_date, 'c');
years_diff = intck('years', start_date, end_date, 'c');
run;
/*view new dataset*/
proc print data=new_data;
Notice the difference between this table and the previous table.
In this table, the difference in weeks between Jan 1st and Jan 9th is calculated as 1 since only one whole week can fit between these dates.
However, in the previous table the difference in weeks was calculated as 2 since there were two partial weeks that fit between these two dates.
Additional Resources
The following tutorials explain how to perform other common tasks in SAS:
How to Convert Datetime to Date in SAS
How to Add Days to Date in SAS
How to Get Day of Week from Date in SAS