December 16, 2007

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

Did you like this post?
kick it on
subscribe via rss subscribe via e-mail
print this post follow me on twitter

About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal



3 Responses to "Difference between two dates"
  1. Alex said...
    June 4, 2009 at 12:24 PM

    Thank you for your post.

  2. prabu said...
    October 21, 2009 at 10:29 PM

    Thank You Dear ....For your Post

  3. Anonymous said...
    August 22, 2012 at 11:44 AM

    Thank you for your post, it was most helpful!


Copyright © 2009-2016 All Rights Reserved for by Suprotim Agarwal | Terms and Conditions