In this post explains how to use the DATEDIFF function in SQL Server (Transact-SQL) with syntax and examples.
In SQL Server (Transact-SQL), the DATEDIFF function returns the difference between two date values, based on the interval specified.
The syntax for the DATEDIFF function in SQL Server (Transact-SQL) is:
DATEDIFF( interval, date1, date2 )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 |
The two dates to calculate the difference between.
The DATEDIFF function can be used in the following versions of SQL Server (Transact-SQL):
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');
Output: 2
SELECT DATEDIFF(yyyy, '2012/04/28', '2014/04/28');
Output: 2
SELECT DATEDIFF(yy, '2012/04/28', '2014/04/28');
Output: 2
SELECT DATEDIFF(month, '2014/01/01', '2014/04/28');
Output: 3
SELECT DATEDIFF(day, '2014/01/01', '2014/04/28');
Output: 117
SELECT DATEDIFF(hour, '2014/04/28 08:00', '2014/04/28 10:45');
Output: 2
SELECT DATEDIFF(minute, '2014/04/28 08:00', '2014/04/28 10:45');
Output: 165