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

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

    Here is a solution.

    DateTime dateOfBirth = new DateTime(2000, 4, 18);
    DateTime currentDate = DateTime.Now;
    
    int ageInYears = 0;
    int ageInMonths = 0;
    int ageInDays = 0;
    
    ageInDays = currentDate.Day - dateOfBirth.Day;
    ageInMonths = currentDate.Month - dateOfBirth.Month;
    ageInYears = currentDate.Year - dateOfBirth.Year;
    
    if (ageInDays < 0)
    {
        ageInDays += DateTime.DaysInMonth(currentDate.Year, currentDate.Month);
        ageInMonths = ageInMonths--;
    
        if (ageInMonths < 0)
        {
            ageInMonths += 12;
            ageInYears--;
        }
    }
    
    if (ageInMonths < 0)
    {
        ageInMonths += 12;
        ageInYears--;
    }
    
    Console.WriteLine("{0}, {1}, {2}", ageInYears, ageInMonths, ageInDays);
    

提交回复
热议问题