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

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

    I've spent some time working on this and came up with this to calculate someone's age in years, months and days. I've tested against the Feb 29th problem and leap years and it seems to work, I'd appreciate any feedback:

    public void LoopAge(DateTime myDOB, DateTime FutureDate)
    {
        int years = 0;
        int months = 0;
        int days = 0;
    
        DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);
    
        DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);
    
        while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate)
        {
            months++;
    
            if (months > 12)
            {
                years++;
                months = months - 12;
            }
        }
    
        if (FutureDate.Day >= myDOB.Day)
        {
            days = days + FutureDate.Day - myDOB.Day;
        }
        else
        {
            months--;
    
            if (months < 0)
            {
                years--;
                months = months + 12;
            }
    
            days +=
                DateTime.DaysInMonth(
                    FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month
                ) + FutureDate.Day - myDOB.Day;
    
        }
    
        //add an extra day if the dob is a leap day
        if (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29)
        {
            //but only if the future date is less than 1st March
            if (FutureDate >= new DateTime(FutureDate.Year, 3, 1))
                days++;
        }
    
    }
    

提交回复
热议问题