Friday, December 01, 2006

Survival: c#, calculate Age given a Birthdate

Need a c# function to calculate an "age" (number of full years) given a Birthdate?
Since I find it really useful... here it is:

public static int GetAge(DateTime BirthDate)
{
    // get the difference in years
    int years = DateTime.Now.Year - BirthDate.Year;
    // subtract another year if we're before the birth day in the current year
    if (DateTime.Now.Month < BirthDate.Month || (DateTime.Now.Month == BirthDate.Month && DateTime.Now.Day < BirthDate.Day))
        years--;

    return years;
}

No comments: