给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?


当前回答

var birthDate = ... // DOB
var resultDate = DateTime.Now - birthDate;

使用resultDate,您可以应用TimeSpan财产来显示任何内容。

其他回答

因为闰年和所有事情,我知道的最好的方法是:

DateTime birthDate = new DateTime(2000,3,1);
int age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D);

这里有一个DateTime扩展程序,它将年龄计算添加到DateTime对象。

public static class AgeExtender
{
    public static int GetAge(this DateTime dt)
    {
        int d = int.Parse(dt.ToString("yyyyMMdd"));
        int t = int.Parse(DateTime.Today.ToString("yyyyMMdd"));
        return (t-d)/10000;
    }
}

我认为TimeSpan包含了我们所需要的一切,而不必求助于365.25(或任何其他近似值)。扩展Aug的示例:

DateTime myBD = new DateTime(1980, 10, 10);
TimeSpan difference = DateTime.Now.Subtract(myBD);

textBox1.Text = difference.Years + " years " + difference.Months + " Months " + difference.Days + " days";
var startDate = new DateTime(2015, 04, 05);//your start date
var endDate = DateTime.Now;
var years = 0;
while(startDate < endDate) 
{
     startDate = startDate.AddYears(1);
     if(startDate < endDate) 
     {
         years++;
     }
}

这个经典问题值得野田时间来解决。

static int GetAge(LocalDate dateOfBirth)
{
    Instant now = SystemClock.Instance.Now;

    // The target time zone is important.
    // It should align with the *current physical location* of the person
    // you are talking about.  When the whereabouts of that person are unknown,
    // then you use the time zone of the person who is *asking* for the age.
    // The time zone of birth is irrelevant!

    DateTimeZone zone = DateTimeZoneProviders.Tzdb["America/New_York"];

    LocalDate today = now.InZone(zone).Date;

    Period period = Period.Between(dateOfBirth, today, PeriodUnits.Years);

    return (int) period.Years;
}

用法:

LocalDate dateOfBirth = new LocalDate(1976, 8, 27);
int age = GetAge(dateOfBirth);

您可能还对以下改进感兴趣:

将时钟作为IClock传递,而不是使用SystemClock.Instance,将提高可测试性。目标时区可能会更改,因此您也需要DateTimeZone参数。

另请参阅我关于这个主题的博客文章:处理生日和其他周年纪念日