给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?
当前回答
这为这个问题提供了“更多细节”。也许这就是你要找的
DateTime birth = new DateTime(1974, 8, 29);
DateTime today = DateTime.Now;
TimeSpan span = today - birth;
DateTime age = DateTime.MinValue + span;
// Make adjustment due to MinValue equalling 1/1/1
int years = age.Year - 1;
int months = age.Month - 1;
int days = age.Day - 1;
// Print out not only how many years old they are but give months and days as well
Console.Write("{0} years, {1} months, {2} days", years, months, days);
其他回答
这个解决方案怎么样?
static string CalcAge(DateTime birthDay)
{
DateTime currentDate = DateTime.Now;
int approximateAge = currentDate.Year - birthDay.Year;
int daysToNextBirthDay = (birthDay.Month * 30 + birthDay.Day) -
(currentDate.Month * 30 + currentDate.Day) ;
if (approximateAge == 0 || approximateAge == 1)
{
int month = Math.Abs(daysToNextBirthDay / 30);
int days = Math.Abs(daysToNextBirthDay % 30);
if (month == 0)
return "Your age is: " + daysToNextBirthDay + " days";
return "Your age is: " + month + " months and " + days + " days"; ;
}
if (daysToNextBirthDay > 0)
return "Your age is: " + --approximateAge + " Years";
return "Your age is: " + approximateAge + " Years"; ;
}
一句话的回答:
DateTime dateOfBirth = Convert.ToDateTime("01/16/1990");
var age = ((DateTime.Now - dateOfBirth).Days) / 365;
因为闰年和所有事情,我知道的最好的方法是:
DateTime birthDate = new DateTime(2000,3,1);
int age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D);
非常简单的答案
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;
我在这个问题上使用了以下内容。我知道它不太优雅,但它很管用。
DateTime zeroTime = new DateTime(1, 1, 1);
var date1 = new DateTime(1983, 03, 04);
var date2 = DateTime.Now;
var dif = date2 - date1;
int years = (zeroTime + dif).Year - 1;
Log.DebugFormat("Years -->{0}", years);