Csharp/C#教程:从C#中的文本框中的日期计算年龄分享


从C#中的文本框中的日期计算年龄

可能重复:
从生日计算年龄

如何计算年龄,以文本框输入格式为dd/MM/yyyy

例如

输入:txtDOB.Text 20/02/1989(字符串格式)
输出:txtAge.Text 23

您可以使用DateTimeSubstract方法( 链接 ),然后使用Days属性来确定实际年龄:

 DateTime now = DateTime.Now; DateTime givenDate = DateTime.Parse(input); int days = now.Subtract(givenDate).Days int age = Math.Floor(days / 365.24219) 

 TimeSpan TS = DateTime.Now - new DateTime(1989, 02, 20); double Years = TS.TotalDays / 365.25; // 365 1/4 days per year 

正如评论中已经提到的,正确的答案在这里: 用C#计算年龄

你只需要将生日作为DateTime:

 DateTime bday = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", CultureInfo.InvariantCulture); 

将出生日期解析为DateTime后,以下内容将起作用:

 static int AgeInYears(DateTime birthday, DateTime today) { return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372; } 

像这样解析日期:

 DateTime dob = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", CultureInfo.InvariantCulture); 

一个示例程序:

 using System; namespace Demo { class Program { static void Main(string[] args) { DateTime dob = new DateTime(2010, 12, 30); DateTime today = DateTime.Now; int age = AgeInYears(dob, today); Console.WriteLine(age); // Prints "1" } static int AgeInYears(DateTime birthday, DateTime today) { return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372; } } } 

这个答案不是最有效的,因为它使用循环,但它也不依赖于使用365.25幻数。

datetime到今天返回整年的函数:

 public static int CalcYears(DateTime fromDate) { int years = 0; DateTime toDate = DateTime.Now; while (toDate.AddYears(-1) >= fromDate) { years++; toDate = toDate.AddYears(-1); } return years; } 

用法:

 int age = CalcYears(DateTime.ParseExact(txtDateOfBirth.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)); 

 var date = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture); var age = (DateTime.Today.Year - date.Year); Console.WriteLine(age); 

试试这个

 string[] AgeVal=textbox.text.split('/'); string Year=AgeVal[2].tostring(); string CurrentYear= DateTime.Now.Date.Year.ToString(); int Age=Convert.ToInt16((Current))-Convert.ToInt16((Year)); 

减去这两个值并得出你的年龄。

上述就是C#学习教程:从C#中的文本框中的日期计算年龄分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1030682.html

(0)
上一篇 2022年1月13日
下一篇 2022年1月13日

精彩推荐