从C#中的文本框中的日期计算年龄
可能重复:
从生日计算年龄
如何计算年龄,以文本框输入格式为dd/MM/yyyy
?
例如
输入:txtDOB.Text 20/02/1989(字符串格式)
输出:txtAge.Text 23
您可以使用DateTime
的Substract
方法( 链接 ),然后使用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));
减去这两个值并得出你的年龄。