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 )

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

About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook


Alex said...

Thank you for your post.

prabu said...

Thank You Dear ....For your Post

Anonymous said...

Thank you for your post, it was most helpful!