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

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

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

30条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 05:26

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

提交回复
热议问题