Pages

Tuesday, February 9, 2010

DATEDIFF Function in SQL Server

In this post i would like to show you to find the difference between two dates using DATEDIFF in SQL Server.

Syntax: DateDiff(DatePart, StartDate, EndDate)

DatePart is the parameter on which SQL Server calculates the difference between two input dates i.e. startdate and enddate.

Please refer to the below table:
Datepart Abbreviations

DatePartAbbreviations
Yearyy, yyyy
quarterqq, q
Monthmm, m
dayofyeardy, y
Daydd, d
Weekwk, ww
Hourhh
minutemi, n
secondss, s
millisecondms

Ex: To calculate the difference between two dates (No Of Days)
SELECT DATEDIFF(DAY,'2001-01-01','2010-01-01') AS No_Of_Days_Difference
Output:
No_Of_Days_Difference

---------------------
3287

Ex: To calculate the difference between two dates (No Of  Years)
SELECT DATEDIFF(YEAR,'2001-01-01','2010-01-01') AS No_Of_Years_Difference
Output:
No_Of_Years_Difference

---------------------
9


Ex: To calculate the difference between two dates (No Of Months)
SELECT DATEDIFF(MONTH,'2001-01-01','2010-01-01') AS No_Of_Months_Difference
Output:
No_Of_Months_Difference
---------------------
108

Reference : Vijaya Kadiyala(www.DotNetVJ.com)

No comments: