当前位置: 首页 > 编程语言 > C#

C#中根据文本框中的日期计算年龄Share

时间:2023-04-10 19:16:59 C#

C#中根据文本框中的日期计算年龄可能重复:根据生日计算年龄如何计算年龄,在文本框中输入格式为dd/MM/yyyy?例如输入:txtDOB.Text20/02/1989(字符串格式)输出:txtAge.Text23可以使用DateTime的Substract方法(链接),然后使用Days属性确定实际年龄:DateTimenow=DateTime.Now;DateTimegivenDate=DateTime.Parse(input);intdays=now.Subtract(givenDate).Daysintage=Math.Floor(days/365.24219)TimeSpanTS=DateTime.Now-newDateTime(1989,02,20);双年=TS.TotalDays/365.25;//每年3651/4天正如评论中已经提到的,正确答案在这里:CalculatingageinC#YoujustneedtogetthebirthdayasaDateTime:DateTimebday=DateTime.ParseExact("20/02/1989","dd/MM/yyyy",CultureInfo.InvariantCulture);将出生日期解析为DateTime后,以下将起作用:staticintAgeInYears(DateTimebirthday,DateTimetoday){return((today.Year-birthday.Year)*372+(today.Month-birthday.Month)*31+(today.Day-birthday.Day))/372;}像这样解析日期:DateTimedob=DateTime.ParseExact("20/02/1989","dd/MM/yyyy",CultureInfo.InvariantCulture);示例程序:使用Syste米;namespaceDemo{classProgram{staticvoidMain(string[]args){DateTimedob=newDateTime(2010,12,30);今天的日期时间=日期时间。现在;intage=AgeInYears(dob,今天);安慰。写行(年龄);//打印“1”}staticintAgeInYears(DateTimebirthday,DateTimetoday){return((today.Year-birthday.Year)*372+(today.Month-birthday.Month)*31+(today.Day-birthday.天))/372;这个答案不是最有效的,因为它使用了一个循环,但它也不依赖于使用365.25幻数返回从日期时间到今天的整年的函数:publicstaticintCalcYears(DateTimefromDate){intyears=0;DateTimetoDate=DateTime.Now;while(toDate.AddYears(-1)>=fromDate){年++;toDate=toDate.AddYears(-1);}返回年;用法:intage=CalcYears(DateTime.ParseExact(txtDateOfBirth.Text,"dd/MM/yyyy",CultureInfo.InvariantCulture));vardate=DateTime.ParseExact("20/02/1989","dd/MM/yyyy",System.Globalization.CultureInfo.InvariantCulture);varage=(DateTime.Today.Year-date.Year);控制台.WriteLine(年龄);试试这个string[]AgeVal=textbox.text.split('/');字符串Year=AgeVal[2].tostring();字符串CurrentYear=DateTime.Now.Date.Year.ToString();intAge=Convert.ToInt16((当前))-Convert.ToInt16((年));将这两个值相减,得到你的年龄。以上就是C#学习教程:根据C#文本框中的日期计算年龄分享的所有内容,如果对大家有用还需要详细了解C#学习教程,希望大家多多关注it——本文来自网络合集,不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: