gotchasqlModerate
How to get exact year difference between two dates in SQL Server?
Viewed 0 times
exactyearsqldatesdifferencetwogetbetweenhowserver
Problem
I have a date of birth column to which I need to compare the current date and return the difference as age. Currently I am using the following query :
I am getting a difference as 15, but the desired result should be 14. This is because it compares the year and gets the difference between 2015 and 2000. So I used the following query :
But when I change the Date Of Birth value to '2000-07-25', I still get the value of 14, but it should be 15 since the date difference is exactly 15 years.
How can I get the exact year difference from this?
DECLARE @DateOfBirth date = '2000-07-27'
DECLARE @CurrentDate date = '2015-07-25'
SELECT
@Age = DATEDIFF(YEAR, @DateOfBirth, @CurrentDate)I am getting a difference as 15, but the desired result should be 14. This is because it compares the year and gets the difference between 2015 and 2000. So I used the following query :
select
@Age = CAST(datediff(day, @DOB, @CurrentDate) / 365.2425 AS INT)
RESULT : 14But when I change the Date Of Birth value to '2000-07-25', I still get the value of 14, but it should be 15 since the date difference is exactly 15 years.
How can I get the exact year difference from this?
Solution
Subtract one from each other in YYYYMMDD format, and divide by 10000 using integer division (which rounds down).
So:
20150725-20000727 = 149998, and 149998 / 10000 = 14
You can also use
So:
(YEAR(@CurrentDate) * 10000 + MONTH(@CurrentDate) * 100 + DAY(@CurrentDate)
- YEAR(@DateOfBirth) * 10000 - MONTH(@DateOfBirth) * 100 - DAY(@DateOfBirth)
) / 1000020150725-20000727 = 149998, and 149998 / 10000 = 14
You can also use
CONVERT(int,CONVERT(char(8),@CurrentDate,112)), because style 112 is YYYYMMDD, but that's a little obfuscated in my opinion.Code Snippets
(YEAR(@CurrentDate) * 10000 + MONTH(@CurrentDate) * 100 + DAY(@CurrentDate)
- YEAR(@DateOfBirth) * 10000 - MONTH(@DateOfBirth) * 100 - DAY(@DateOfBirth)
) / 10000Context
StackExchange Database Administrators Q#108078, answer score: 17
Revisions (0)
No revisions yet.