How to calculate an age based on a birthday?

nacho10f picture nacho10f · Feb 3, 2010 · Viewed 107.9k times · Source

Possible Duplicate:
How do I calculate someone’s age in C#?

I want to write an ASP.NET helper method which returns the age of a person given his or her birthday.

I've tried code like this:

public static string Age(this HtmlHelper helper, DateTime birthday)
{
    return (DateTime.Now - birthday); //??
}

But it's not working. What is the correct way to calculate the person's age based on their birthday?

Answer

Pierre-Alain Vigeant picture Pierre-Alain Vigeant · Feb 3, 2010

Stackoverflow uses such function to determine the age of a user.

Calculate age in C#

The given answer is

DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;

So your helper method would look like

public static string Age(this HtmlHelper helper, DateTime birthday)
{
    DateTime now = DateTime.Today;
    int age = now.Year - birthday.Year;
    if (now < birthday.AddYears(age)) age--;

    return age.ToString();
}

Today, I use a different version of this function to include a date of reference. This allow me to get the age of someone at a future date or in the past. This is used for our reservation system, where the age in the future is needed.

public static int GetAge(DateTime reference, DateTime birthday)
{
    int age = reference.Year - birthday.Year;
    if (reference < birthday.AddYears(age)) age--;

    return age;
}