如何以dd/MM/yyyy
e.g。
输入:txtDOB.Text 20/02/1989(字符串格式)
输出:txtAge.Text 23
答案 0 :(得分:3)
您可以使用Substract
(link)的DateTime
方法,然后使用Days
属性来确定实际年龄:
DateTime now = DateTime.Now;
DateTime givenDate = DateTime.Parse(input);
int days = now.Subtract(givenDate).Days
int age = Math.Floor(days / 365.24219)
答案 1 :(得分:0)
正如评论中已经提到的,正确的答案在这里:Calculate age in C#
你只需要将生日作为日期时间:
DateTime bday = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", CultureInfo.InvariantCulture);
答案 2 :(得分:0)
TimeSpan TS = DateTime.Now - new DateTime(1989, 02, 20);
double Years = TS.TotalDays / 365.25; // 365 1/4 days per year
答案 3 :(得分:-1)
将您的出生日期解析为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;
}
}
}
答案 4 :(得分:-1)
这个答案不是最有效的,因为它使用循环,但它不依赖于使用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));
答案 5 :(得分:-2)
var date = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
var age = (DateTime.Today.Year - date.Year);
Console.WriteLine(age);
答案 6 :(得分:-3)
试试这个
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));
减去这两个值并获得你的年龄。