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

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

提交回复
热议问题