Difference between two dates

One of the most common requirement encountered is to find the difference between two dates. In Sql 2005, we can achieve this requirement easily by using the DATEDIFF() function.

DATEDIFF() returns a value in datepart format, specifying the difference between two specified dates.

Syntax : DATEDIFF ( datepart , startdate , enddate )

Eg:
SELECT OrderID,CustomerID,OrderDate,
DATEDIFF(yy, OrderDate, GETDATE()) YearsPassedSinceOrder
FROM Northwind.dbo.Orders

returns the no. of years passed since the order was placed.

Similarly to find number of months, use 'm' as the datepart or 'd' to determine no. of days.

You can find other values for datepart over here

3 comments: