DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Calculate Age In C#

03.04.2006
| 59652 views |
  • submit to reddit
        using System;
using System.Data;

public static class Snippets
{
    public static int CalculateAge(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;
    }
}
    

Comments

Jason McDonald replied on Wed, 2007/05/16 - 8:11pm

The snippet will have a problem is the date changes during execution. Cache the "now" date and reuse it for each comparison so that it will not change. As a low-level speed optimization, change years-- to --years. Fixed: public static class Snippets { public static int CalculateAge(DateTime birthDate) { // cache the current time DateTime now = DateTime.Today; // today is fine, don't need the timestamp from now // get the difference in years int years = now.Year - birthDate.Year; // subtract another year if we're before the // birth day in the current year if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) --years; return years; } }