c# - How do I calculate someone's age based on a DateTime type birthday?

ID : 424

viewed : 230

Tags : c#.netdatetimec#

Top 5 Answer for c# - How do I calculate someone's age based on a DateTime type birthday?

vote vote

99

An easy to understand and simple solution.

// Save today's date. var today = DateTime.Today;  // Calculate the age. var age = today.Year - birthdate.Year;  // Go back to the year in which the person was born in case of a leap year if (birthdate.Date > today.AddYears(-age)) age--; 

However, this assumes you are looking for the western idea of the age and not using East Asian reckoning.

vote vote

88

This is a strange way to do it, but if you format the date to yyyymmdd and subtract the date of birth from the current date then drop the last 4 digits you've got the age :)

I don't know C#, but I believe this will work in any language.

20080814 - 19800703 = 280111  

Drop the last 4 digits = 28.

C# Code:

int now = int.Parse(DateTime.Now.ToString("yyyyMMdd")); int dob = int.Parse(dateOfBirth.ToString("yyyyMMdd")); int age = (now - dob) / 10000; 

Or alternatively without all the type conversion in the form of an extension method. Error checking omitted:

public static Int32 GetAge(this DateTime dateOfBirth) {     var today = DateTime.Today;      var a = (today.Year * 100 + today.Month) * 100 + today.Day;     var b = (dateOfBirth.Year * 100 + dateOfBirth.Month) * 100 + dateOfBirth.Day;      return (a - b) / 10000; } 
vote vote

78

Here is a test snippet:

DateTime bDay = new DateTime(2000, 2, 29); DateTime now = new DateTime(2009, 2, 28); MessageBox.Show(string.Format("Test {0} {1} {2}",                 CalculateAgeWrong1(bDay, now),      // outputs 9                 CalculateAgeWrong2(bDay, now),      // outputs 9                 CalculateAgeCorrect(bDay, now),     // outputs 8                 CalculateAgeCorrect2(bDay, now)));  // outputs 8 

Here you have the methods:

public int CalculateAgeWrong1(DateTime birthDate, DateTime now) {     return new DateTime(now.Subtract(birthDate).Ticks).Year - 1; }  public int CalculateAgeWrong2(DateTime birthDate, DateTime now) {     int age = now.Year - birthDate.Year;      if (now < birthDate.AddYears(age))         age--;      return age; }  public int CalculateAgeCorrect(DateTime birthDate, DateTime now) {     int age = now.Year - birthDate.Year;      if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))         age--;      return age; }  public int CalculateAgeCorrect2(DateTime birthDate, DateTime now) {     int age = now.Year - birthDate.Year;      // For leap years we need this     if (birthDate > now.AddYears(-age))          age--;     // Don't use:     // if (birthDate.AddYears(age) > now)      //     age--;      return age; } 
vote vote

62

The simple answer to this is to apply AddYears as shown below because this is the only native method to add years to the 29th of Feb. of leap years and obtain the correct result of the 28th of Feb. for common years.

Some feel that 1th of Mar. is the birthday of leaplings but neither .Net nor any official rule supports this, nor does common logic explain why some born in February should have 75% of their birthdays in another month.

Further, an Age method lends itself to be added as an extension to DateTime. By this you can obtain the age in the simplest possible way:

  1. List item

int age = birthDate.Age();

public static class DateTimeExtensions {     /// <summary>     /// Calculates the age in years of the current System.DateTime object today.     /// </summary>     /// <param name="birthDate">The date of birth</param>     /// <returns>Age in years today. 0 is returned for a future date of birth.</returns>     public static int Age(this DateTime birthDate)     {         return Age(birthDate, DateTime.Today);     }      /// <summary>     /// Calculates the age in years of the current System.DateTime object on a later date.     /// </summary>     /// <param name="birthDate">The date of birth</param>     /// <param name="laterDate">The date on which to calculate the age.</param>     /// <returns>Age in years on a later day. 0 is returned as minimum.</returns>     public static int Age(this DateTime birthDate, DateTime laterDate)     {         int age;         age = laterDate.Year - birthDate.Year;          if (age > 0)         {             age -= Convert.ToInt32(laterDate.Date < birthDate.Date.AddYears(age));         }         else         {             age = 0;         }          return age;     } } 

Now, run this test:

class Program {     static void Main(string[] args)     {         RunTest();     }      private static void RunTest()     {         DateTime birthDate = new DateTime(2000, 2, 28);         DateTime laterDate = new DateTime(2011, 2, 27);         string iso = "yyyy-MM-dd";          for (int i = 0; i < 3; i++)         {             for (int j = 0; j < 3; j++)             {                 Console.WriteLine("Birth date: " + birthDate.AddDays(i).ToString(iso) + "  Later date: " + laterDate.AddDays(j).ToString(iso) + "  Age: " + birthDate.AddDays(i).Age(laterDate.AddDays(j)).ToString());             }         }          Console.ReadKey();     } } 

The critical date example is this:

Birth date: 2000-02-29 Later date: 2011-02-28 Age: 11

Output:

{     Birth date: 2000-02-28  Later date: 2011-02-27  Age: 10     Birth date: 2000-02-28  Later date: 2011-02-28  Age: 11     Birth date: 2000-02-28  Later date: 2011-03-01  Age: 11     Birth date: 2000-02-29  Later date: 2011-02-27  Age: 10     Birth date: 2000-02-29  Later date: 2011-02-28  Age: 11     Birth date: 2000-02-29  Later date: 2011-03-01  Age: 11     Birth date: 2000-03-01  Later date: 2011-02-27  Age: 10     Birth date: 2000-03-01  Later date: 2011-02-28  Age: 10     Birth date: 2000-03-01  Later date: 2011-03-01  Age: 11 } 

And for the later date 2012-02-28:

{     Birth date: 2000-02-28  Later date: 2012-02-28  Age: 12     Birth date: 2000-02-28  Later date: 2012-02-29  Age: 12     Birth date: 2000-02-28  Later date: 2012-03-01  Age: 12     Birth date: 2000-02-29  Later date: 2012-02-28  Age: 11     Birth date: 2000-02-29  Later date: 2012-02-29  Age: 12     Birth date: 2000-02-29  Later date: 2012-03-01  Age: 12     Birth date: 2000-03-01  Later date: 2012-02-28  Age: 11     Birth date: 2000-03-01  Later date: 2012-02-29  Age: 11     Birth date: 2000-03-01  Later date: 2012-03-01  Age: 12 } 
vote vote

51

My suggestion

int age = (int) ((DateTime.Now - bday).TotalDays/365.242199); 

That seems to have the year changing on the right date. (I spot tested up to age 107.)

Top 3 video Explaining c# - How do I calculate someone's age based on a DateTime type birthday?

Related QUESTION?