如何根据生日计算年龄?

可能重复:
如何计算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(); } 

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

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

}

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

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

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