.NET life

HUGON Jérôme
Microsoft Certified Technology Specialist Microsoft Certified Application Developer Microsoft Certified Professional

Calculating an age from a date of birth

.NET

Category .NET  | Publication Date : 9/21/2009

Calculate someone's age is quite helpful. Here's a function to perform the calculation. To make the code work, you need a object DateTime called birthdate containing the anniversary date.

C#.NET:

public static int CalculateAge(DateTime birthdate)
{
    int years = DateTime.Now.Year - birthdate.Year;
    if (DateTime.Now.Month < birthdate.Month 
    || (DateTime.Now.Month == birthdate.Month 
        && DateTime.Now.Day < birthdate.Day))
        years--;
    return years;
}

VB.NET:

Public Shared Function CalculateAge(ByVal birthdate As DateTime) As Integer
    Dim years As Integer = DateTime.Now.Year - birthdate.Year
    If (DateTime.Now.Month < birthdate.Month Or (DateTime.Now.Month = birthdate.Month And DateTime.Now.Day < birthdate.Day)) Then
        years = years - 1
    End If
    Return years
End Function