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, yy | Year interval |
quarter, qq, q | Quarter interval |
month, mm, m | Month interval |
dayofyear | Day of year interval |
day, dy, y | Day interval |
week, ww, wk | Week interval |
weekday, dw, w | Weekday interval |
hour, hh | Hour interval |
minute, mi, n | Minute interval |
second, ss, s | Second interval |
millisecond, ms | Millisecond 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