如何根据生日计算年龄?

时间:2010-02-03 19:59:32

标签: c# asp.net-mvc date-arithmetic

  

可能重复:
  How do I calculate someone’s age in C#?

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

我尝试过这样的代码:

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

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

4 个答案:

答案 0 :(得分:43)

Stackoverflow使用此类函数来确定用户的年龄。

Calculate age in C#

给出的答案是

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;
}

答案 1 :(得分:6)

另一个聪明的方法ancient thread

int age = (
    Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
    Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;

答案 2 :(得分: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...

}

答案 3 :(得分:-2)

我真的不明白你为什么要把它变成HTML帮助器。我会把它作为控制器的动作方法中的ViewData字典的一部分。像这样:

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

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