How to calculate an age based on a birthday?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
How do I calculate someone’s age in C#?
我想编写一个ASP.NET助手方法,该方法返回给定生日的人的年龄。
我试过这样的代码:
1 2 3 4 | public static string Age(this HtmlHelper helper, DateTime birthday) { return (DateTime.Now - birthday); //?? } |
但它不起作用。根据生日计算年龄的正确方法是什么?
StackOverflow使用这样的函数来确定用户的年龄。
以C为单位计算年龄#
给出的答案是
1 2 3 | DateTime now = DateTime.Today; int age = now.Year - bday.Year; if (now < bday.AddYears(age)) age--; |
所以你的助手方法看起来像
1 2 3 4 5 6 7 8 | 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(); } |
今天,我使用此函数的另一个版本来包含引用日期。这让我可以在未来的某个日期或过去了解某人的年龄。这是用于我们的预订系统,在那里需要未来的年龄。
1 2 3 4 5 6 7 | public static int GetAge(DateTime reference, DateTime birthday) { int age = reference.Year - birthday.Year; if (reference < birthday.AddYears(age)) age--; return age; } |
另一个巧妙的方法是:
1 2 3 | int age = ( Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000; |
我是这样做的:
(代码缩短了一点)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | 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字典的一部分放在控制器的操作方法中。像这样:
1 | ViewData["Age"] = DateTime.Now.Year - birthday.Year; |
假定生日被传递到一个操作方法中,并且是一个日期时间对象。