DATEDIFF Function in SQL Server

DATEDIFF Function in SQL Server

The DATEDIFF Function is used to calculate the difference between two dates. So let’s have a look at a practical example of how to use a DATEDIFF Function in SQL Server

The DATEDIFF Function

The SQL Server DATEDIFF Function is used to calculate the difference between two dates.  

Syntax

The syntax of the DATEDIFF built-in date function is as follows :

DATEDIFF(Datepart, Startdate, Enddate)

Here, The “Datepart” parameter is the part of the datetime to calculate the difference of. The Datepart can be any of the following:

Ms         Milliseconds
Yy          Year
Qq         Quarter of the Year
Mm        Month
Dy          The Day of the Year
Dd         Day of the Month
Wk         Week
Dw         The Day of the Week
Hh          Hour
Mi          Minute
Ss           Second


Example-1


Now you can calculate age with the DATEDIFF function:


Select  getdate() as CurrentDate


Go


Declare @CurrentDate datetime = getdate()


Declare @DOB datetime = ‘1986-03-15’


Select  DATEDIFF( Year, @DOB, @CurrentDate) as CurrentAgeinYears


Output

Calculate-age-using-DateDiff-Function-in-SQL-Server


 


Example-2


Now you can see when the second date is later than the first date. The result will be a negative number:


Select datediff(YY,  ‘2012-08-05’, ‘2008-06-05’) As Year


Go


Select datediff(Mm,  ‘2012-08-05’, ‘2008-06-05’) As Month


Output

Second-Date-is-Bigger-Than-The-First-Date-using-DateDiff-Function-in-SQL-Server


 

 

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply