How can I calculate the age of a person in year, month, days?

前端 未结 11 1186
谎友^
谎友^ 2020-11-27 05:52

I want to calculate the age of a person given the date of birth and the current date in years, months and days relative to the current date.

For example:

<         


        
11条回答
  •  遥遥无期
    2020-11-27 06:37

    Here is this using the borrowing rule of mathematics.

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

提交回复
热议问题