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
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;
}
}





Comments
Jason McDonald replied on Wed, 2007/05/16 - 8:11pm
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; } }