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

后端 未结 30 2165
名媛妹妹
名媛妹妹 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);
    
    0 讨论(0)
  • 2020-11-21 05:45

    I have a customized method to calculate age, plus a bonus validation message just in case it helps:

    public void GetAge(DateTime dob, DateTime now, out int years, out int months, out int days)
    {
        years = 0;
        months = 0;
        days = 0;
    
        DateTime tmpdob = new DateTime(dob.Year, dob.Month, 1);
        DateTime tmpnow = new DateTime(now.Year, now.Month, 1);
    
        while (tmpdob.AddYears(years).AddMonths(months) < tmpnow)
        {
            months++;
            if (months > 12)
            {
                years++;
                months = months - 12;
            }
        }
    
        if (now.Day >= dob.Day)
            days = days + now.Day - dob.Day;
        else
        {
            months--;
            if (months < 0)
            {
                years--;
                months = months + 12;
            }
            days += DateTime.DaysInMonth(now.AddMonths(-1).Year, now.AddMonths(-1).Month) + now.Day - dob.Day;
        }
    
        if (DateTime.IsLeapYear(dob.Year) && dob.Month == 2 && dob.Day == 29 && now >= new DateTime(now.Year, 3, 1))
            days++;
    
    }   
    
    private string ValidateDate(DateTime dob) //This method will validate the date
    {
        int Years = 0; int Months = 0; int Days = 0;
    
        GetAge(dob, DateTime.Now, out Years, out Months, out Days);
    
        if (Years < 18)
            message =  Years + " is too young. Please try again on your 18th birthday.";
        else if (Years >= 65)
            message = Years + " is too old. Date of Birth must not be 65 or older.";
        else
            return null; //Denotes validation passed
    }
    

    Method call here and pass out datetime value (MM/dd/yyyy if server set to USA locale). Replace this with anything a messagebox or any container to display:

    DateTime dob = DateTime.Parse("03/10/1982");  
    
    string message = ValidateDate(dob);
    
    lbldatemessage.Visible = !StringIsNullOrWhitespace(message);
    lbldatemessage.Text = message ?? ""; //Ternary if message is null then default to empty string
    

    Remember you can format the message any way you like.

    0 讨论(0)
  • 2020-11-21 05:48

    The following approach (extract from Time Period Library for .NET class DateDiff) considers the calendar of the culture info:

    // ----------------------------------------------------------------------
    private static int YearDiff( DateTime date1, DateTime date2 )
    {
      return YearDiff( date1, date2, DateTimeFormatInfo.CurrentInfo.Calendar );
    } // YearDiff
    
    // ----------------------------------------------------------------------
    private static int YearDiff( DateTime date1, DateTime date2, Calendar calendar )
    {
      if ( date1.Equals( date2 ) )
      {
        return 0;
      }
    
      int year1 = calendar.GetYear( date1 );
      int month1 = calendar.GetMonth( date1 );
      int year2 = calendar.GetYear( date2 );
      int month2 = calendar.GetMonth( date2 );
    
      // find the the day to compare
      int compareDay = date2.Day;
      int compareDaysPerMonth = calendar.GetDaysInMonth( year1, month1 );
      if ( compareDay > compareDaysPerMonth )
      {
        compareDay = compareDaysPerMonth;
      }
    
      // build the compare date
      DateTime compareDate = new DateTime( year1, month2, compareDay,
        date2.Hour, date2.Minute, date2.Second, date2.Millisecond );
      if ( date2 > date1 )
      {
        if ( compareDate < date1 )
        {
          compareDate = compareDate.AddYears( 1 );
        }
      }
      else
      {
        if ( compareDate > date1 )
        {
          compareDate = compareDate.AddYears( -1 );
        }
      }
      return year2 - calendar.GetYear( compareDate );
    } // YearDiff
    

    Usage:

    // ----------------------------------------------------------------------
    public void CalculateAgeSamples()
    {
      PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2009, 02, 28 ) );
      // > Birthdate=29.02.2000, Age at 28.02.2009 is 8 years
      PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2012, 02, 28 ) );
      // > Birthdate=29.02.2000, Age at 28.02.2012 is 11 years
    } // CalculateAgeSamples
    
    // ----------------------------------------------------------------------
    public void PrintAge( DateTime birthDate, DateTime moment )
    {
      Console.WriteLine( "Birthdate={0:d}, Age at {1:d} is {2} years", birthDate, moment, YearDiff( birthDate, moment ) );
    } // PrintAge
    
    0 讨论(0)
  • 2020-11-21 05:50

    This is the version we use here. It works, and it's fairly simple. It's the same idea as Jeff's but I think it's a little clearer because it separates out the logic for subtracting one, so it's a little easier to understand.

    public static int GetAge(this DateTime dateOfBirth, DateTime dateAsAt)
    {
        return dateAsAt.Year - dateOfBirth.Year - (dateOfBirth.DayOfYear < dateAsAt.DayOfYear ? 0 : 1);
    }
    

    You could expand the ternary operator to make it even clearer, if you think that sort of thing is unclear.

    Obviously this is done as an extension method on DateTime, but clearly you can grab that one line of code that does the work and put it anywhere. Here we have another overload of the Extension method that passes in DateTime.Now, just for completeness.

    0 讨论(0)
  • 2020-11-21 05:50

    The simplest way I've ever found is this. It works correctly for the US and western europe locales. Can't speak to other locales, especially places like China. 4 extra compares, at most, following the initial computation of age.

    public int AgeInYears(DateTime birthDate, DateTime referenceDate)
    {
      Debug.Assert(referenceDate >= birthDate, 
                   "birth date must be on or prior to the reference date");
    
      DateTime birth = birthDate.Date;
      DateTime reference = referenceDate.Date;
      int years = (reference.Year - birth.Year);
    
      //
      // an offset of -1 is applied if the birth date has 
      // not yet occurred in the current year.
      //
      if (reference.Month > birth.Month);
      else if (reference.Month < birth.Month) 
        --years;
      else // in birth month
      {
        if (reference.Day < birth.Day)
          --years;
      }
    
      return years ;
    }
    

    I was looking over the answers to this and noticed that nobody has made reference to regulatory/legal implications of leap day births. For instance, per Wikipedia, if you're born on February 29th in various jurisdictions, you're non-leap year birthday varies:

    • In the United Kingdom and Hong Kong: it's the ordinal day of the year, so the next day, March 1st is your birthday.
    • In New Zealand: it's the previous day, February 28th for the purposes of driver licencing, and March 1st for other purposes.
    • Taiwan: it's February 28th.

    And as near as I can tell, in the US, the statutes are silent on the matter, leaving it up to the common law and to how various regulatory bodies define things in their regulations.

    To that end, an improvement:

    public enum LeapDayRule
    {
      OrdinalDay     = 1 ,
      LastDayOfMonth = 2 ,
    }
    
    static int ComputeAgeInYears(DateTime birth, DateTime reference, LeapYearBirthdayRule ruleInEffect)
    {
      bool isLeapYearBirthday = CultureInfo.CurrentCulture.Calendar.IsLeapDay(birth.Year, birth.Month, birth.Day);
      DateTime cutoff;
    
      if (isLeapYearBirthday && !DateTime.IsLeapYear(reference.Year))
      {
        switch (ruleInEffect)
        {
          case LeapDayRule.OrdinalDay:
            cutoff = new DateTime(reference.Year, 1, 1)
                                 .AddDays(birth.DayOfYear - 1);
            break;
    
          case LeapDayRule.LastDayOfMonth:
            cutoff = new DateTime(reference.Year, birth.Month, 1)
                                 .AddMonths(1)
                                 .AddDays(-1);
            break;
    
          default:
            throw new InvalidOperationException();
        }
      }
      else
      {
        cutoff = new DateTime(reference.Year, birth.Month, birth.Day);
      }
    
      int age = (reference.Year - birth.Year) + (reference >= cutoff ? 0 : -1);
      return age < 0 ? 0 : age;
    }
    

    It should be noted that this code assumes:

    • A western (European) reckoning of age, and
    • A calendar, like the Gregorian calendar that inserts a single leap day at the end of a month.
    0 讨论(0)
  • 2020-11-21 05:50

    I used ScArcher2's solution for an accurate Year calculation of a persons age but I needed to take it further and calculate their Months and Days along with the Years.

        public static Dictionary<string,int> CurrentAgeInYearsMonthsDays(DateTime? ndtBirthDate, DateTime? ndtReferralDate)
        {
            //----------------------------------------------------------------------
            // Can't determine age if we don't have a dates.
            //----------------------------------------------------------------------
            if (ndtBirthDate == null) return null;
            if (ndtReferralDate == null) return null;
    
            DateTime dtBirthDate = Convert.ToDateTime(ndtBirthDate);
            DateTime dtReferralDate = Convert.ToDateTime(ndtReferralDate);
    
            //----------------------------------------------------------------------
            // Create our Variables
            //----------------------------------------------------------------------
            Dictionary<string, int> dYMD = new Dictionary<string,int>();
            int iNowDate, iBirthDate, iYears, iMonths, iDays;
            string sDif = "";
    
            //----------------------------------------------------------------------
            // Store off current date/time and DOB into local variables
            //---------------------------------------------------------------------- 
            iNowDate = int.Parse(dtReferralDate.ToString("yyyyMMdd"));
            iBirthDate = int.Parse(dtBirthDate.ToString("yyyyMMdd"));
    
            //----------------------------------------------------------------------
            // Calculate Years
            //----------------------------------------------------------------------
            sDif = (iNowDate - iBirthDate).ToString();
            iYears = int.Parse(sDif.Substring(0, sDif.Length - 4));
    
            //----------------------------------------------------------------------
            // Store Years in Return Value
            //----------------------------------------------------------------------
            dYMD.Add("Years", iYears);
    
            //----------------------------------------------------------------------
            // Calculate Months
            //----------------------------------------------------------------------
            if (dtBirthDate.Month > dtReferralDate.Month)
                iMonths = 12 - dtBirthDate.Month + dtReferralDate.Month - 1;
            else
                iMonths = dtBirthDate.Month - dtReferralDate.Month;
    
            //----------------------------------------------------------------------
            // Store Months in Return Value
            //----------------------------------------------------------------------
            dYMD.Add("Months", iMonths);
    
            //----------------------------------------------------------------------
            // Calculate Remaining Days
            //----------------------------------------------------------------------
            if (dtBirthDate.Day > dtReferralDate.Day)
                //Logic: Figure out the days in month previous to the current month, or the admitted month.
                //       Subtract the birthday from the total days which will give us how many days the person has lived since their birthdate day the previous month.
                //       then take the referral date and simply add the number of days the person has lived this month.
    
                //If referral date is january, we need to go back to the following year's December to get the days in that month.
                if (dtReferralDate.Month == 1)
                    iDays = DateTime.DaysInMonth(dtReferralDate.Year - 1, 12) - dtBirthDate.Day + dtReferralDate.Day;       
                else
                    iDays = DateTime.DaysInMonth(dtReferralDate.Year, dtReferralDate.Month - 1) - dtBirthDate.Day + dtReferralDate.Day;       
            else
                iDays = dtReferralDate.Day - dtBirthDate.Day;             
    
            //----------------------------------------------------------------------
            // Store Days in Return Value
            //----------------------------------------------------------------------
            dYMD.Add("Days", iDays);
    
            return dYMD;
    }
    
    0 讨论(0)
提交回复
热议问题