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

后端 未结 30 2171
名媛妹妹
名媛妹妹 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:53

    This is one of the most accurate answers that is able to resolve the birthday of 29th of Feb compared to any year of 28th Feb.

    public int GetAge(DateTime birthDate)
    {
        int age = DateTime.Now.Year - birthDate.Year;
    
        if (birthDate.DayOfYear > DateTime.Now.DayOfYear)
            age--;
    
        return age;
    }
    
    
    
    
    

提交回复
热议问题