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

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

    How about this solution?

    static string CalcAge(DateTime birthDay)
    {
        DateTime currentDate = DateTime.Now;         
        int approximateAge = currentDate.Year - birthDay.Year;
        int daysToNextBirthDay = (birthDay.Month * 30 + birthDay.Day) - 
            (currentDate.Month * 30 + currentDate.Day) ;
    
        if (approximateAge == 0 || approximateAge == 1)
        {                
            int month =  Math.Abs(daysToNextBirthDay / 30);
            int days = Math.Abs(daysToNextBirthDay % 30);
    
            if (month == 0)
                return "Your age is: " + daysToNextBirthDay + " days";
    
            return "Your age is: " + month + " months and " + days + " days"; ;
        }
    
        if (daysToNextBirthDay > 0)
            return "Your age is: " + --approximateAge + " Years";
    
        return "Your age is: " + approximateAge + " Years"; ;
    }
    

提交回复
热议问题