给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?
当前回答
2需要解决的主要问题有:
1.计算准确年龄-以年、月、日等为单位。
2.计算人们普遍认为的年龄——人们通常不关心自己到底多大,他们只关心自己当年的生日是什么时候。
1的解决方案显而易见:
DateTime birth = DateTime.Parse("1.1.2000");
DateTime today = DateTime.Today; //we usually don't care about birth time
TimeSpan age = today - birth; //.NET FCL should guarantee this as precise
double ageInDays = age.TotalDays; //total number of days ... also precise
double daysInYear = 365.2425; //statistical value for 400 years
double ageInYears = ageInDays / daysInYear; //can be shifted ... not so precise
2的解决方案在确定总年龄时并不那么精确,但人们认为它是精确的。当人们“手动”计算年龄时,通常也会使用它:
DateTime birth = DateTime.Parse("1.1.2000");
DateTime today = DateTime.Today;
int age = today.Year - birth.Year; //people perceive their age in years
if (today.Month < birth.Month ||
((today.Month == birth.Month) && (today.Day < birth.Day)))
{
age--; //birthday in current year not yet reached, we are 1 year younger ;)
//+ no birthday for 29.2. guys ... sorry, just wrong date for birth
}
注释2.:
这是我的首选解决方案我们不能使用DateTime.DayOfYear或TimeSpans,因为它们会在闰年中改变天数为了可读性,我只增加了几行
还有一个提示。。。我将为它创建两个静态重载方法,一个用于通用,另一个用于使用友好:
public static int GetAge(DateTime bithDay, DateTime today)
{
//chosen solution method body
}
public static int GetAge(DateTime birthDay)
{
return GetAge(birthDay, DateTime.Now);
}
其他回答
这里有一个非常简单且易于遵循的示例。
private int CalculateAge()
{
//get birthdate
DateTime dtBirth = Convert.ToDateTime(BirthDatePicker.Value);
int byear = dtBirth.Year;
int bmonth = dtBirth.Month;
int bday = dtBirth.Day;
DateTime dtToday = DateTime.Now;
int tYear = dtToday.Year;
int tmonth = dtToday.Month;
int tday = dtToday.Day;
int age = tYear - byear;
if (bmonth < tmonth)
age--;
else if (bmonth == tmonth && bday>tday)
{
age--;
}
return age;
}
这可能会起作用:
public override bool IsValid(DateTime value)
{
_dateOfBirth = value;
var yearsOld = (double) (DateTime.Now.Subtract(_dateOfBirth).TotalDays/365);
if (yearsOld > 18)
return true;
return false;
}
我使用这个:
public static class DateTimeExtensions
{
public static int Age(this DateTime birthDate)
{
return Age(birthDate, DateTime.Now);
}
public static int Age(this DateTime birthDate, DateTime offsetDate)
{
int result=0;
result = offsetDate.Year - birthDate.Year;
if (offsetDate.DayOfYear < birthDate.DayOfYear)
{
result--;
}
return result;
}
}
这是最准确的答案之一,它能够解决2月29日的生日,而不是2月28日的任何一年。
public int GetAge(DateTime birthDate)
{
int age = DateTime.Now.Year - birthDate.Year;
if (birthDate.DayOfYear > DateTime.Now.DayOfYear)
age--;
return age;
}
哇,我不得不在这里回答。。。这么简单的问题有很多答案。
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;
}