25

可能重复:
如何根据 DateTime 类型的生日计算某人的年龄?

我想编写一个 ASP.NET 辅助方法,它返回一个人的年龄,给他或她的生日。

我试过这样的代码:

public static string Age(this HtmlHelper helper, DateTime birthday)
{
    return (DateTime.Now - birthday); //??
}

但它不起作用。根据生日计算人的年龄的正确方法是什么?

4

4 回答 4

44

Stack Overflow 使用这样的函数来确定用户的年龄。

如何根据 DateTime 类型的生日计算某人的年龄?

给出的答案是

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-03T20:05:20.773 回答
6

从那个古老的线程中获得另一种聪明的方法:

int age = (
    Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
    Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;
于 2010-02-03T20:21:41.280 回答
2

我这样做:

(稍微缩短了代码)

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...

}

于 2010-02-03T20:15:49.823 回答
-3

我真的不明白你为什么要把它设为 HTML Helper。我会在控制器的操作方法中使其成为 ViewData 字典的一部分。像这样的东西:

ViewData["Age"] = DateTime.Now.Year - birthday.Year;

鉴于生日被传递到一个操作方法并且是一个 DateTime 对象。

于 2010-02-03T20:03:34.200 回答