我想写返回给他或她的生日一个人的年龄的ASP.NET的辅助方法。
我已经试过这样的代码:
public static string Age(this HtmlHelper helper, DateTime birthday)
{
return (DateTime.Now - birthday); //??
}
但它不工作。根据生日计算人的年龄的正确方法是什么?
我想写返回给他或她的生日一个人的年龄的ASP.NET的辅助方法。
我已经试过这样的代码:
public static string Age(this HtmlHelper helper, DateTime birthday)
{
return (DateTime.Now - birthday); //??
}
但它不工作。根据生日计算人的年龄的正确方法是什么?
Stackoverflow使用这样的函数来确定用户的年龄。
给出的答案是
DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;
所以,你的helper方法看起来像
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;
}
我真的不明白你为什么要把这个HTML Helper。我将它作为控制器的操作方法中的ViewData字典的一部分。类似这样的:
ViewData["Age"] = DateTime.Now.Year - birthday.Year;
鉴于生日是传递给一个操作方法并且是一个DateTime对象。
没有按如果有人出生在''不工作“2009-12-31''; ''2010-01-01''已经有一年了? – 2010-02-03 20:12:32
正如所说的,如果这个人是在1月1日出生的话,那就永远是正确的。在任何其他情况下,如果当前的月/日不在出生日的月/日之后,将会出现结果错误的日期。 – 2013-11-04 22:46:55
我不喜欢这样写道:
(缩短了代码位)
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...
}
从ancient thread另一种巧妙的方式:
int age = (
Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) -
Int32.Parse(birthday.ToString("yyyyMMdd")))/10000;
为什么不只是'新的DateTime(DateTime.Now.Subtract(birthDate.Ticks).Year-1'? – 2010-02-03 20:24:30
在附注中,未来的生日会有什么正确的行为?返回一个负数?抛出?从字面上看,昨天出生的人的年龄是0岁? – 2010-02-03 20:28:07
@Steven还没有出生的人应该总是年龄为0,imo。 你在那年只有1年的时间。在2000年,我们庆祝了日期的变化,但2000年仅在2001年初才完成,所以我们应该在2001年初庆祝2000年,而不是在2000年初。 – 2010-02-03 20:40:36