In C#, how do I calculate someone's age based on a DateTime type birthday?

后端 未结 30 2173
名媛妹妹
名媛妹妹 2020-11-21 05:14

Given a DateTime representing a person\'s birthday, how do I calculate their age in years?

30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 05:27

    2 Main problems to solve are:

    1. Calculate Exact age - in years, months, days, etc.

    2. Calculate Generally perceived age - people usually do not care how old they exactly are, they just care when their birthday in the current year is.


    Solution for 1 is obvious:

    DateTime birth = DateTime.Parse("1.1.2000");
    DateTime today = DateTime.Today;     //we usually don't care about birth time
    TimeSpan age = today - birth;        //.NET FCL should guarantee this as precise
    double ageInDays = age.TotalDays;    //total number of days ... also precise
    double daysInYear = 365.2425;        //statistical value for 400 years
    double ageInYears = ageInDays / daysInYear;  //can be shifted ... not so precise
    

    Solution for 2 is the one which is not so precise in determing total age, but is perceived as precise by people. People also usually use it, when they calculate their age "manually":

    DateTime birth = DateTime.Parse("1.1.2000");
    DateTime today = DateTime.Today;
    int age = today.Year - birth.Year;    //people perceive their age in years
    
    if (today.Month < birth.Month ||
       ((today.Month == birth.Month) && (today.Day < birth.Day)))
    {
      age--;  //birthday in current year not yet reached, we are 1 year younger ;)
              //+ no birthday for 29.2. guys ... sorry, just wrong date for birth
    }
    

    Notes to 2.:

    • This is my preferred solution
    • We cannot use DateTime.DayOfYear or TimeSpans, as they shift number of days in leap years
    • I have put there little more lines for readability

    Just one more note ... I would create 2 static overloaded methods for it, one for universal usage, second for usage-friendliness:

    public static int GetAge(DateTime bithDay, DateTime today) 
    { 
      //chosen solution method body
    }
    
    public static int GetAge(DateTime birthDay) 
    { 
      return GetAge(birthDay, DateTime.Now);
    }
    

提交回复
热议问题