如何根据生日来计算年龄?

可能重复:
我如何用C#计算某人的年龄?

我想编写一个ASP.NET帮助程序方法,该方法返回给定生日的人的年龄。

我试过这样的代码:

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

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


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

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

来自古老线索的另一个聪明的方式:

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

我这样做:

(缩短了一下代码)

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

}

链接地址: http://www.djcxy.com/p/54347.html

上一篇: How to calculate an age based on a birthday?

下一篇: Date difference in years using C#