Never been to DZone Snippets before?

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

Calculate age in C# (See related posts)

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 on this post

jokeyxero posts on May 16, 2007 at 20:17
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;
    }
}

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts