ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Age

Get the actual age of a person

Source

static public int Age(this DateTime dateOfBirth) {
     if (DateTime.Today.Month < dateOfBirth.Month ||
	 DateTime.Today.Month == dateOfBirth.Month &&
	  DateTime.Today.Day < dateOfBirth.Day) {
          return DateTime.Today.Year - dateOfBirth.Year - 1;
	} else
	 return DateTime.Today.Year - dateOfBirth.Year;
}

Example

DateTime henrybirthdate = new DateTime(1998,10,12);

int age = henrybirthdate.Age();

Author: Detlef Meyer

Submitted on: 7 feb. 2009

Language: C#

Type: System.DateTime

Views: 11789