How do I calculate age from date of birth?

DATEDIFF is the function to use. However, if the birth date hasn’t yet occurred this year, the age calculated by DATEDIFF will be off by 1. For example, imagine your birthday is Dec 31st and you were born in 1950. If today is Oct 1st, 2000, subtracting the year portions of the two dates (2000-1950) would indicate that your were 50 years old. DATEDIFF returns an integer representing the number of date parts between two dates. If the start date falls after the end date, the result is negative. DATEDIFF only counts boundaries. Hence when we calculate how many years elapsed between December 31, 1999, and January 1, 2001, we will get, "2."

Here is the calculation using DATEDIFF and not accounting for whether the birth date has been reached this year:

DECLARE @BIRTHDATE SMALLDATETIME, @AGE SMALLDATETIME
SELECT @BIRTHDATE='12/10/1990', @AGE='6/24/2001'
SELECT DATEDIFF(YY,@BIRTHDATE,@AGE) AS 'Calculate age using straight DATEDIFF'


This is one way we can fix the above query:

SELECT DATEDIFF (YY, @BIRTHDATE, @AGE) -
CASE WHEN (MONTH(@BIRTHDATE)=MONTH(@AGE) AND DAY(@BIRTHDATE) > DAY(@AGE)
OR MONTH (@BIRTHDATE) > MONTH (@AGE))
THEN 1 ELSE 0 END AS 'Calculate age correcting DATEDIFF'


Here are the results:

Calculate age using straight DATEDIFF
11

Calculate age correcting DATEDIFF
10

Back

 
Printer friendly version of the FAQ-TSQL-Calculate-Age page


Sponsored links

Build IT Knowledge with Current & Trusted Content
Helps Employees Develop & Hone New Technical Programming Skills. Sign Up & Get Full Access.
Check Out IT Certification Preparation Materials
Sign Up With SkillSoft & Get Access to Training Materials for Over 50 Professional Certifications.
Villanova University Six Sigma & IT Certificate Programs
100% Online programs in Six Sigma, IS Security, CISSP Prep, Business Analysis, Proj. Mgmt. and more!
Key Elements to an Effective Business Continuity Plan
Learn to develop a plan that clarifies what is critical and sets specific recovery requirements.
Web based bug tracking - AdminiTrack.com
AdminiTrack offers an effective web-based bug tracking system designed for professional software development teams.

Advertisement



Free Magazine

Free Magazines
eWeek The essential technology information source for builders of e-business.... subscribe now

Newsletter | Submit Content | About | Advertising | Awards | Contact Us | Link to us |
© 1996-2008 Community Networks Ltd All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Synchron Data - .NET development.