Date differences

The DATEDIFF function calculates the difference between two date values and returns an integer (with any fraction component truncated) in the specified date/time units. The general form of the expression is

DATEDIFF(datetime2, datetime1, “unit”).

where datetime2 and datetime1 are both date or time format variables (or numeric values that represent valid date/time values), and “unit” is one of the following string literal values, enclosed in quotes:

  • Years
  • Quarters
  • Months
  • Weeks
  • Days
  • Hours
  • Minutes
  • Seconds

Example

DATA LIST FREE /date1 date2 (2ADATE10).
BEGIN DATA
1/1/2004 2/1/2005
1/1/2004 2/15/2005
1/30/2004 1/29/2005
END DATA.
COMPUTE years=DATEDIFF(date2, date1, "years").
  • The result will be the integer portion of the number of years between the two dates, with any fractional component truncated.
  • One "year" is defined as the same month and day, one year before or after the second date argument.
  • For the first two cases, the result is 1, since in both cases the number of years is greater than or equal to 1 and less than 2.
  • For the third case, the result is 0, since the difference is one day short of a year based on the definition of year.

Example

DATA LIST FREE /date1 date2 (2ADATE10).
BEGIN DATA
1/1/2004 2/1/2004
1/1/2004 2/15/2004
1/30/2004 2/1/2004
END DATA.
COMPUTE months=DATEDIFF(date2, date1, "months").
  • The result will be the integer portion of the number of months between the two dates, with any fractional component truncated.
  • One "month" is defined as the same day of the month, one calendar month before or after the second date argument.
  • For the first two cases, the result will be 1, since both February 1 and February 15, 2004, are greater than or equal to one month and less than two months after January 1, 2004.
  • For the third case, the result will be 0. By definition, any date in February 2004 will be less than one month after January 30, 2004, resulting in a value of 0.