|
Execute the following SQL Server T-SQL example script in Management Studio Query Editor to calculate the difference between two dates in years, months and days.
-- SQL calculate length of service in years, months, days - SQL calculate age
-- SQL calculating duration between two dates
-- SQL datediff datetime function - SQL dateadd datetime function
USE AdventureWorks;
DECLARE @EndDate DATETIME,
@Anniversary DATETIME,
@StartDate DATETIME,
@YYDelta INT,
@MMDelta INT,
@DDDelta INT
SET @StartDate = '2000-01-01'
SET @EndDate = Getdate()
SET @Anniversary =
Dateadd(yy,Datediff(yy,@StartDate,@EndDate),@StartDate)
SET @YYDelta = Datediff(yy,@StartDate,@EndDate) -
(CASE
WHEN @Anniversary > @EndDate THEN 1 ELSE 0 END)
SET @MMDelta = Month(@EndDate - @Anniversary) - 1
SET @DDDelta = Day(@EndDate - @Anniversary) - 1
SELECT Years = @YYDelta,
Months = @MMDelta,
[Days] = @DDDelta
GO
/* Results
Years Months Days
9 1 19
*/
------------ |