给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?
当前回答
public string GetAge(this DateTime birthdate, string ageStrinFormat = null)
{
var date = DateTime.Now.AddMonths(-birthdate.Month).AddDays(-birthdate.Day);
return string.Format(ageStrinFormat ?? "{0}/{1}/{2}",
(date.Year - birthdate.Year), date.Month, date.Day);
}
其他回答
我的建议
int age = (int) ((DateTime.Now - bday).TotalDays/365.242199);
这一年似乎在正确的日期发生了变化。(我在107岁之前进行了现场测试。)
这里有一个单行线:
int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;
通过较少的转换和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
);
}
我经常用手指数。我需要看一下日历,以确定事情何时发生变化。这就是我在代码中要做的:
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中的代码在这里。
可以这么简单:
int age = DateTime.Now.AddTicks(0 - dob.Ticks).Year - 1;