Daily Archives: September 2, 2009

Calculate age (for instance, on reference data)

Now and then, I have to calculate ages (for instance, on a reference date). The method to calculate ages in .NET is pretty simple, although it can be ‘a pain in the ass’ to find out how simple it should have been :) … Enjoy the code :) !

public static class DateTimeHelper
{
    public static int CalculateAge(DateTime birthday)
    {
        return CalculateAge(DateTime.Now, birthday);
    }

    public static int CalculateAge(DateTime referenceDate, DateTime birthday)
    {
        // calculate age in years on the given reference date.
        var comparisonDate = new DateTime(birthday.Year, referenceDate.Month, referenceDate.Day);

        return (comparisonDate.Date < birthday.Date)
                      ? referenceDate.Year - birthday.Year - 1
                      : referenceDate.Year - birthday.Year;
    }
}