如何根据生日计算年龄?
可能重复:
如何计算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对象。
上述就是C#学习教程:如何根据生日计算年龄?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/991349.html