可能重复:
How do I calculate someone's age based on a DateTime type birthday?
我想要写一个ASP.NET助手方法,返回一个人的年龄,给他或她的生日。
我试过这样的代码:
public static string Age(this HtmlHelper helper, DateTime birthday)
{
return (DateTime.Now - birthday); //??
}但这不管用。根据一个人的生日来计算年龄的正确方法是什么?
发布于 2010-02-03 20:05:20
堆栈溢出使用这样的函数来确定用户的年龄。
给出的答案是
DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age))
age--;因此,您的助手方法看起来如下:
public static string Age(this HtmlHelper helper, DateTime birthday)
{
DateTime now = DateTime.Today;
int age = now.Year - birthday.Year;
if (now < birthday.AddYears(age))
age--;
return age.ToString();
}今天,我使用这个函数的另一个版本来包含一个参考日期。这允许我在未来的日期或过去获得某人的年龄。这是用于我们的预订系统,在那里,年龄在未来是需要的。
public static int GetAge(DateTime reference, DateTime birthday)
{
int age = reference.Year - birthday.Year;
if (reference < birthday.AddYears(age))
age--;
return age;
}发布于 2010-02-03 20:21:41
ancient thread的另一种聪明的方法
int age = (
Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) -
Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;发布于 2010-02-03 20:15:49
我这样做:
(代码缩短了一点)
public struct Age
{
public readonly int Years;
public readonly int Months;
public readonly int Days;
}
public Age( int y, int m, int d ) : this()
{
Years = y;
Months = m;
Days = d;
}
public static Age CalculateAge ( DateTime birthDate, DateTime anotherDate )
{
if( startDate.Date > endDate.Date )
{
throw new ArgumentException ("startDate cannot be higher then endDate", "startDate");
}
int years = endDate.Year - startDate.Year;
int months = 0;
int days = 0;
// Check if the last year, was a full year.
if( endDate < startDate.AddYears (years) && years != 0 )
{
years--;
}
// Calculate the number of months.
startDate = startDate.AddYears (years);
if( startDate.Year == endDate.Year )
{
months = endDate.Month - startDate.Month;
}
else
{
months = ( 12 - startDate.Month ) + endDate.Month;
}
// Check if last month was a complete month.
if( endDate < startDate.AddMonths (months) && months != 0 )
{
months--;
}
// Calculate the number of days.
startDate = startDate.AddMonths (months);
days = ( endDate - startDate ).Days;
return new Age (years, months, days);
}
// Implement Equals, GetHashCode, etc... as well
// Overload equality and other operators, etc...}
https://stackoverflow.com/questions/2194999
复制相似问题