SQL Server: DATEDIFF Function

DATEDIFF function 

This SQL Server tutorial explains how to use the DATEDIFF function in SQL Server (Transact-SQL) with syntax and examples.

Description

In SQL Server (Transact-SQL), the DATEDIFF function returns the difference between two date values, based on the interval specified.

Syntax

The syntax for the DATEDIFF function in SQL Server (Transact-SQL) is:

DATEDIFF( interval, date1, date2 )

Parameters or Arguments

interval

The interval of time to use to calculate the difference between date1 and date2. It can be one of the following values:

Value (any one of)Explanation
year, yyyy, yyYear interval
quarter, qq, qQuarter interval
month, mm, mMonth interval
dayofyearDay of year interval
day, dy, yDay interval
week, ww, wkWeek interval
weekday, dw, wWeekday interval
hour, hhHour interval
minute, mi, nMinute interval
second, ss, sSecond interval
millisecond, msMillisecond interval

date1, date2The two dates to calculate the difference between.

Applies To

The DATEDIFF function can be used in the following versions of SQL Server (Transact-SQL):

  • SQL Server 2017, SQL Server 2016, SQL Server 2014, SQL Server 2012, SQL Server 2008 R2, SQL Server 2008, SQL Server 2005

Example

Let’s look at some SQL Server DATEDIFF function examples and explore how to use the DATEDIFF function in SQL Server (Transact-SQL).

For example:

SELECT DATEDIFF(year, '2012/04/28', '2014/04/28');
Result: 2

SELECT DATEDIFF(yyyy, '2012/04/28', '2014/04/28');
Result: 2

SELECT DATEDIFF(yy, '2012/04/28', '2014/04/28');
Result: 2

SELECT DATEDIFF(month, '2014/01/01', '2014/04/28');
Result: 3

SELECT DATEDIFF(day, '2014/01/01', '2014/04/28');
Result: 117

SELECT DATEDIFF(hour, '2014/04/28 08:00', '2014/04/28 10:45');
Result: 2

SELECT DATEDIFF(minute, '2014/04/28 08:00', '2014/04/28 10:45');
Result: 165

Leave a Reply