如何根据生日计算年龄?

nac*_*10f 22 c# asp.net-mvc date-arithmetic

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

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

我尝试过这样的代码:

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

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

Pie*_*ant 43

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

用C#计算年龄

给出的答案是

DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;
Run Code Online (Sandbox Code Playgroud)

所以你的助手方法看起来像

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();
}
Run Code Online (Sandbox Code Playgroud)

今天,我使用此功能的不同版本来包含参考日期.这允许我在未来的日期或过去获得某人的年龄.这用于我们的预订系统,需要未来的年龄.

public static int GetAge(DateTime reference, DateTime birthday)
{
    int age = reference.Year - birthday.Year;
    if (reference < birthday.AddYears(age)) age--;

    return age;
}
Run Code Online (Sandbox Code Playgroud)


Rub*_*ias 6

从那个古老的线程的另一个聪明的方法:

int age = (
    Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
    Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;
Run Code Online (Sandbox Code Playgroud)