Calculating an Age in C# From a Date of Birth - Hilton Giesenow's Jumbled Mind

Hilton Giesenow's Jumbled Mind

the madness that is...

News

This is my little spot in cyberspace where you will find a collection of random (but mostly software-related) thoughts and ideas that are frightening in their shining brilliance (or something like that ;->).
 
Please enjoy your stay and feel free to Contact Me.
 
Microsoft MVP

.Net Links

BlogRoll

Misc. Links

Syndication

Calculating an Age in C# From a Date of Birth

Just a quickie - if you've got a date of birth, you can get and age using the following formula. It's based on the code at http://www.developerfusion.co.uk/show/4671/, but I've simplified it a bit:

// get the difference in years

int years = DateTime.Now.Year - dateOfBirthDate.Year;

// subtract another year if we're before the

// birth day in the current year

dateOfBirthDate = dateOfBirthDate.AddYears(years);

if (DateTime.Now.CompareTo(dateOfBirthDate) < 0) { years--; }

return years;

Posted: Jul 25 2005, 12:22 PM by hiltong | with 7 comment(s)
Filed under:

Comments

Andres Olivares said:

Couldn't you just simplify it via:

return (int)((double)new TimeSpan(DateTime.Now.Subtract(dob).Ticks).Days / 365.25);

any [dob] over Now would not be an age, so you could check your age result is not < 0 after calculation

# November 10, 2006 8:40 PM

hiltong said:

Nice one, thanks

# November 11, 2006 10:32 PM

Fudo said:

this i my function: what do you think ?

int i=new DateTime(2008, 12, 31).AddYears(1).AddTicks(-1*new DateTime(2008, 1, 1).Ticks).Year-1;

# July 13, 2007 12:23 PM

Justin Crawford said:

I extended the logic to produce months & days for the age:

public static string FormatAge(DateTime start, DateTime end)

{

// Compute the difference between start

//year and end year.

int years = end.Year - start.Year;

int months = 0;

int days = 0;

// Check if the last year was a full year.

if (end < start.AddYears(years) && years != 0)

{

   --years;

}

start = start.AddYears(years);

// Now we know start <= end and the diff between them

// is < 1 year.

if (start.Year == end.Year)

{

   months = end.Month - start.Month;

}

else

{

   months = (12 - start.Month) + end.Month;

}

// Check if the last month was a full month.

if (end < start.AddMonths(months) && months != 0)

{

   --months;

}

start = start.AddMonths(months);

// Now we know that start < end and is within 1 month

// of each other.

days = (end - start).Days;

return years + "years " + months

   + " months " + days + " days";

}

# July 19, 2007 12:25 AM

LA.NET [EN] said:

Today I’ll keep writing about the new Code Contracts platform and we’ll see how we can use the write

# November 6, 2008 9:01 PM

ASPInsiders said:

Today I’ll keep writing about the new Code Contracts platform and we’ll see how we can use the write

# November 6, 2008 9:31 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: