SQL Server DATEDIFF()Function


SQL DatesSQL Server Date Functions

Definition and Usage

The DATEDIFF() function returns the interval between two dates.

The DATEDIFF() function is a date function in SQL Server used to calculate the time interval between two dates. It takes three parameters: the interval unit, the start date, and the end date, and returns the unit time interval between the two dates.

Syntax

DATEDIFF(interval, start_date, end_date)

The start_date and end_date parameters are valid date expressions.

The interval parameter can be one of the following values:

  • year: year
  • quarter: quarter
  • month: month
  • dayofyear: day of year
  • day: day
  • week: week
  • weekday: weekday
  • hour: hour
  • minute: minute
  • second: second
  • millisecond: millisecond


Example

Now we want to get the number of days between two dates.

We use the following SELECT statement:

SELECT DATEDIFF(day,'2008-06-05','2008-08-05') AS DiffDate

Result:

DiffDate
61

Example

Now we want to get the number of days between two dates (note that since the second date is earlier than the first, the result will be a negative number).

We use the following SELECT statement:

SELECT DATEDIFF(day,'2008-08-05','2008-06-05') AS DiffDate

Result:

DiffDate
-61


SQL DatesSQL Server Date Functions Other Extensions