Pages

Men

rh

7/17/2012

DATEDIFF FUNCTION in SQL Server

DATEDIFF  FUNCTION 
This is used to find out the difference between two DateTime elements.


Get the count of number of Days between 2 dates  
 
Example:
declare @RegDate datetime
declare @CurrentDate datetime
set  @RegDate = '2012-05-1 00:00:00.000'
set  @CurrentDate = '2012-07-17 09:58:06.240'
 
select DATEDIFF ( day , @RegDate , @CurrentDate ) as NumberOfDays

Ouput:
NumberOfDays:
77
 
Get the count of number of months between 2 dates
 
Example:
declare @RegDate datetime
declare @CurrentDate datetime
set  @RegDate = '2012-05-1 00:00:00.000'
set  @CurrentDate = '2012-07-17 09:58:06.240'

SELECT DATEDIFF (month, @RegDate, @CurrentDate) AS NumberOfMonths

Output: 
NumberOfMonths
2

Get the count of number of years between 2 dates

Example:-
declare @RegDate datetime
declare @CurrentDate datetime
set  @RegDate = '2001-05-1 00:00:00.000'
set  @CurrentDate = '2012-07-17 09:58:06.240'

SELECT DATEDIFF (Year, @RegDate, @CurrentDate) AS NumberOfYears

Output:-
NumberOfYears
11

 

Back

No comments :

Post a Comment