给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?
当前回答
简单代码
var birthYear=1993;
var age = DateTime.Now.AddYears(-birthYear).Year;
其他回答
哇,我不得不在这里回答。。。这么简单的问题有很多答案。
private int CalcularIdade(DateTime dtNascimento)
{
var nHoje = Convert.ToInt32(DateTime.Today.ToString("yyyyMMdd"));
var nAniversario = Convert.ToInt32(dtNascimento.ToString("yyyyMMdd"));
double diff = (nHoje - nAniversario) / 10000;
var ret = Convert.ToInt32(Math.Truncate(diff));
return ret;
}
因为闰年和所有事情,我知道的最好的方法是:
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;
}
}
无分支解决方案:
public int GetAge(DateOnly birthDate, DateOnly today)
{
return today.Year - birthDate.Year + (((today.Month << 5) + today.Day - ((birthDate.Month << 5) + birthDate.Day)) >> 31);
}
==常见说法(从几个月到几岁)===
如果您只是为了通用,以下是代码作为您的信息:
DateTime today = DateTime.Today;
DateTime bday = DateTime.Parse("2016-2-14");
int age = today.Year - bday.Year;
var unit = "";
if (bday > today.AddYears(-age))
{
age--;
}
if (age == 0) // Under one year old
{
age = today.Month - bday.Month;
age = age <= 0 ? (12 + age) : age; // The next year before birthday
age = today.Day - bday.Day >= 0 ? age : --age; // Before the birthday.day
unit = "month";
}
else {
unit = "year";
}
if (age > 1)
{
unit = unit + "s";
}
测试结果如下:
The birthday: 2016-2-14
2016-2-15 => age=0, unit=month;
2016-5-13 => age=2, unit=months;
2016-5-14 => age=3, unit=months;
2016-6-13 => age=3, unit=months;
2016-6-15 => age=4, unit=months;
2017-1-13 => age=10, unit=months;
2017-1-14 => age=11, unit=months;
2017-2-13 => age=11, unit=months;
2017-2-14 => age=1, unit=year;
2017-2-15 => age=1, unit=year;
2017-3-13 => age=1, unit=year;
2018-1-13 => age=1, unit=year;
2018-1-14 => age=1, unit=year;
2018-2-13 => age=1, unit=year;
2018-2-14 => age=2, unit=years;