Over a million developers have joined DZone.

Calculate Age In C#

·
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;
    }
}
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}