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)
- interval: Interval to calculate (day, week, month, year, etc.)
- start date: The start date
- end date: The end date
- method: Whether to count complete intervals (‘D’ = No (Default), ‘C’ = Yes)
The following example shows how to use this function in practice.
Example : 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 14AUG2022 ; 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, and months:
/*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); run; /*view new dataset*/ proc print data=new_data;
The three new variables show the difference between start_date and end_date in days, weeks, and months.
Note that we can use the ‘c‘ argument in the INTCK function to only calculate the difference in complete days, weeks, and months:
/*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'); 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.
The following tutorials explain how to perform other common tasks in SAS:
How to Normalize Data in SAS
How to Replace Characters in a String in SAS
How to Replace Missing Values with Zero in SAS
How to Remove Duplicates in SAS