Calculate age using C#

Calculate age using C#
An efficient C# method for calculating the age in years by passing in the birth date.
public static int CalculateAge(DateTime BirthDate)
{
    int YearsPassed = DateTime.Now.Year - BirthDate.Year;
    // Are we before the birth date this year? If so subtract one year from the mix
    if (DateTime.Now.Month < BirthDate.Month || (DateTime.Now.Month == BirthDate.Month && DateTime.Now.Day < BirthDate.Day))
    {
        YearsPassed--;
    }
    return YearsPassed;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top