C# calculate accurate age

前端 未结 14 1803
攒了一身酷
攒了一身酷 2020-12-15 11:01

anyone know how to get the age based on a date(birthdate)

im thinking of something like this

string age = DateTime.Now.GetAccurateAge();
14条回答
  •  一个人的身影
    2020-12-15 11:55

    I was noticing peculiarities with LukeH's answer and leap years. The simplest example is probably a dob = 2/29/2016 as of 2/28/2017 and 3/1/2017. The way I look at it, there are no days left in Feb 2016, there are 11 complete months (Mar-Jan) in between, and there have been 28 days in Feb 2017 so far, so as of 2/28/2017, I would call this person 11 months 28 days old. And 1 year 1 day old as of 3/1/2017. (Although some leap day babies do celebrate and on the 28th of common years ... I'm curious what the legal consideration is.)

    Because LukeH's method makes uses of DateTime.AddMonths, it calculates 11 months 30 days, because it finds the difference in days between 2/28/2017 and 1/29/2017. So it calculates that 2/28/2017 is 11 mo 30 days after 2/29/2016, and 11 mo 27 days after 3/1/2016. A 3 day age difference for birthdays only 1 day apart. If it came up with 28 days as I did "by hand" they would have a one day age difference.

    I'm not exactly sure how to describe the fundamental difference in approaches, but here is my stab at it. It seems there is always a gotcha with dates so please scrutinize.

    internal static void CalculateAge(DateTime dateOfBirth, DateTime asOfDate, out int years, out int months, out int days)
    {
        Console.Write("As of " + asOfDate.ToShortDateString() + ": ");
    
        //Get the relative difference between each date part
        days = asOfDate.Day - dateOfBirth.Day;
        months = asOfDate.Month - dateOfBirth.Month;
        years = asOfDate.Year - dateOfBirth.Year;
    
        if (days < 0)
        {
            days = DateTime.DaysInMonth(dateOfBirth.Year, dateOfBirth.Month) - dateOfBirth.Day +    //Days left in month of birthday +
                    asOfDate.Day;                                                                   //Days passed in asOfDate's month
            months--;                                                                               //Subtract incomplete month that was already counted
        }
    
        if (months < 0)
        {
            months += 12;   //Subtract months from 12 to convert relative difference to # of months
            years--;        //Subtract incomplete year that was already counted
        }
    
        Console.WriteLine(string.Format("{0} year{1}, {2} month{3} and {4} day{5}",
                    years, (years == 1) ? "" : "s",
                    months, (months == 1) ? "" : "s",
                    days, (days == 1) ? "" : "s"));
    }
    

提交回复
热议问题