Click here to Skip to main content
16,016,814 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
select datediff(yy,'1986-12-06','2003-10-12 14:55:49.480')as years
this gives me age as 17 years now i need to consider if it is only two months remaining in completing 18 years how would i do this.Please suggest
Posted
Comments
Sergey Alexandrovich Kryukov 13-Jun-13 1:45am    
Did you try anything?
—SA
shriti 3 13-Jun-13 1:50am    
yes i tried using Datepart function but not getting how exactly i consider it as 18 years

Well, think on the age in months: who is going to be 18 in two months, is 18*12-2=214 months old.
SQL
...datediff(mm,...
 
Share this answer
 
Ages are not quite the same as dates, and the real problem is that you are accessing the number of years - which is an integer value, and only considers the year number in the calculation. So
SQL
SELECT datediff(yy,'1986-01-01','2003-12-31') AS years
And
SELECT datediff(yy,'1986-01-01','2003-01-01') AS years
SQL

Will also both return 17.

A solution is to use the number of months:
SQL
SELECT datediff(mm,'1986-01-01','2003-12-31') AS months
which is a little better - you can compare the number of months against 18 * 12, but it's still not that helpfull if you need to have an exact cut off date at 18 years:
SQL
SELECT datediff(mm,'2003-11-30','2003-12-01')AS months
returns 1 for example.

A better solution is to add the years to the start date:
SQL
SELECT DATEDIFF(dd, DATEADD(yy, 18, '1986-12-06'), '2013-10-12') as DAYS

If the result is negative they are under 18, if it's greater than zero they are over 18, and if it is zero it's their 18th birthday!
 
Share this answer
 
Comments
shriti 3 13-Jun-13 2:14am    
Thanks alot
shriti 3 13-Jun-13 2:29am    
but i need to consider the person who is only two months less in completing 18 years
OriginalGriff 13-Jun-13 2:40am    
So use two DATEADD operations: the first adds +18 years, second adds -2 months.
OriginalGriff 13-Jun-13 2:39am    
You're welecome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900