给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?
当前回答
试试这个解决方案,它奏效了。
int age = (Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) -
Int32.Parse(birthday.ToString("yyyyMMdd rawrrr"))) / 10000;
其他回答
==常见说法(从几个月到几岁)===
如果您只是为了通用,以下是代码作为您的信息:
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;
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++;
}
}
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);
}
这可能会起作用:
public override bool IsValid(DateTime value)
{
_dateOfBirth = value;
var yearsOld = (double) (DateTime.Now.Subtract(_dateOfBirth).TotalDays/365);
if (yearsOld > 18)
return true;
return false;
}
我只想这样做:
DateTime birthDay = new DateTime(1990, 05, 23);
DateTime age = DateTime.Now - birthDay;
这样你就可以计算出一个人的确切年龄,如果你愿意的话,可以精确到毫秒。