给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?
当前回答
非常简单的答案
DateTime dob = new DateTime(1991, 3, 4);
DateTime now = DateTime.Now;
int dobDay = dob.Day, dobMonth = dob.Month;
int add = -1;
if (dobMonth < now.Month)
{
add = 0;
}
else if (dobMonth == now.Month)
{
if(dobDay <= now.Day)
{
add = 0;
}
else
{
add = -1;
}
}
else
{
add = -1;
}
int age = now.Year - dob.Year + add;
其他回答
我认为这个问题可以用这样一种更简单的方法解决-
该类可以是-
using System;
namespace TSA
{
class BirthDay
{
double ageDay;
public BirthDay(int day, int month, int year)
{
DateTime birthDate = new DateTime(year, month, day);
ageDay = (birthDate - DateTime.Now).TotalDays; //DateTime.UtcNow
}
internal int GetAgeYear()
{
return (int)Math.Truncate(ageDay / 365);
}
internal int GetAgeMonth()
{
return (int)Math.Truncate((ageDay % 365) / 30);
}
}
}
电话可以是这样的-
BirthDay b = new BirthDay(1,12,1990);
int year = b.GetAgeYear();
int month = b.GetAgeMonth();
这是最准确的答案之一,它能够解决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;
}
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);
}
可以这么简单:
int age = DateTime.Now.AddTicks(0 - dob.Ticks).Year - 1;
非常简单的答案
DateTime dob = new DateTime(1991, 3, 4);
DateTime now = DateTime.Now;
int dobDay = dob.Day, dobMonth = dob.Month;
int add = -1;
if (dobMonth < now.Month)
{
add = 0;
}
else if (dobMonth == now.Month)
{
if(dobDay <= now.Day)
{
add = 0;
}
else
{
add = -1;
}
}
else
{
add = -1;
}
int age = now.Year - dob.Year + add;