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


当前回答

通过较少的转换和UtcNow,这段代码可以照顾闰年2月29日出生的人:

public int GetAge(DateTime DateOfBirth)
{
    var Now = DateTime.UtcNow;
    return Now.Year - DateOfBirth.Year -
        (
            (
                Now.Month > DateOfBirth.Month ||
                (Now.Month == DateOfBirth.Month && Now.Day >= DateOfBirth.Day)
            ) ? 0 : 1
        );
}

其他回答

简单易懂的解决方案。

// Save today's date.
var today = DateTime.Today;

// Calculate the age.
var age = today.Year - birthdate.Year;

// Go back to the year in which the person was born in case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;

然而,这假设你在寻找西方的时代观念,而不是使用东亚的推算法。

int Age = new DateTime((DateTime.Now - BirthDate).Ticks).Year -1;
Console.WriteLine("Age {0}", Age);
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++;
     }
}

可以这么简单:

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

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