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


当前回答

TimeSpan diff = DateTime.Now - birthdayDateTime;
string age = String.Format("{0:%y} years, {0:%M} months, {0:%d}, days old", diff);

我不知道你到底希望它返回给你多少,所以我只是做了一个可读的字符串。

其他回答

以下是计算某人年龄的最简单方法。计算某人的年龄非常简单,下面是计算方法!为了使代码正常工作,您需要一个名为BirthDate的DateTime对象,该对象包含生日。

 C#
        // get the difference in years
        int years = DateTime.Now.Year - BirthDate.Year; 
        // subtract another year if we're before the
        // birth day in the current year
        if (DateTime.Now.Month < BirthDate.Month || 
            (DateTime.Now.Month == BirthDate.Month && 
            DateTime.Now.Day < BirthDate.Day)) 
            years--;
  VB.NET
        ' get the difference in years
        Dim years As Integer = DateTime.Now.Year - BirthDate.Year
        ' subtract another year if we're before the
        ' birth day in the current year
        If DateTime.Now.Month < BirthDate.Month Or (DateTime.Now.Month = BirthDate.Month And DateTime.Now.Day < BirthDate.Day) Then 
            years = years - 1
        End If

简单代码

 var birthYear=1993;
 var age = DateTime.Now.AddYears(-birthYear).Year;

我经常用手指数。我需要看一下日历,以确定事情何时发生变化。这就是我在代码中要做的:

int AgeNow(DateTime birthday)
{
    return AgeAt(DateTime.Now, birthday);
}

int AgeAt(DateTime now, DateTime birthday)
{
    return AgeAt(now, birthday, CultureInfo.CurrentCulture.Calendar);
}

int AgeAt(DateTime now, DateTime birthday, Calendar calendar)
{
    // My age has increased on the morning of my
    // birthday even though I was born in the evening.
    now = now.Date;
    birthday = birthday.Date;

    var age = 0;
    if (now <= birthday) return age; // I am zero now if I am to be born tomorrow.

    while (calendar.AddYears(birthday, age + 1) <= now)
    {
        age++;
    }
    return age;
}

在LINQPad中运行此过程可获得以下结果:

PASSED: someone born on 28 February 1964 is age 4 on 28 February 1968
PASSED: someone born on 29 February 1964 is age 3 on 28 February 1968
PASSED: someone born on 31 December 2016 is age 0 on 01 January 2017

LINQPad中的代码在这里。

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

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

要使用最近的年龄计算年龄:

var ts = DateTime.Now - new DateTime(1988, 3, 19);
var age = Math.Round(ts.Days / 365.0);