如何计算基于一个生日年龄? [英] How to calculate an age based on a birthday?
问题描述
可能重复:结果
如何计算某人&rsquo的;年龄在C#中 <? / p>
块引用>我想写返回给他或她的生日一个人的年龄一个ASP.NET的辅助方法。
我试过code是这样的:
公共静态字符串年龄(这个的HtmlHelper助手,日期生日)
{
返回(DateTime.Now - 生日); //?
}但它不工作。什么是基于他们的生日来计算人的年龄的正确方法是什么?
解决方案#1使用这样的功能来确定用户的年龄。
给出的答案是
现在的DateTime = DateTime.Today;
INT年龄= now.Year - bday.Year;
如果(现&LT; bday.AddYears(年龄))age--;所以,你的helper方法看起来像
公共静态字符串年龄(这个的HtmlHelper助手,日期生日)
{
现在的DateTime = DateTime.Today;
INT年龄= now.Year - birthday.Year;
如果(现&LT; birthday.AddYears(年龄))age--; 返回age.ToString();
}今天,我用不同版本的功能,包括一个参考日期。这让我找人的年龄在未来某一日期或过去。这是用于我们的预约系统中,其中需要在年龄在将来
公共静态INT GetAge(DateTime的参考,日期生日)
{
INT年龄= reference.Year - birthday.Year;
如果(参考&LT; birthday.AddYears(年龄))age--; 返回年龄;
}Possible Duplicate:
How do I calculate someone’s age in C#?I want to write an ASP.NET helper method which returns the age of a person given his or her birthday.
I've tried code like this:
public static string Age(this HtmlHelper helper, DateTime birthday) { return (DateTime.Now - birthday); //?? }
But it's not working. What is the correct way to calculate the person's age based on their birthday?
解决方案Stackoverflow uses such function to determine the age of a user.
How do I calculate someone's age in C#?
The given answer is
DateTime now = DateTime.Today; int age = now.Year - bday.Year; if (now < bday.AddYears(age)) age--;
So your helper method would look like
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(); }
Today, I use a different version of this function to include a date of reference. This allow me to get the age of someone at a future date or in the past. This is used for our reservation system, where the age in the future is needed.
public static int GetAge(DateTime reference, DateTime birthday) { int age = reference.Year - birthday.Year; if (reference < birthday.AddYears(age)) age--; return age; }
这篇关于如何计算基于一个生日年龄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!