如何从c中的dob计算年龄(以年为单位)
本文关键字:为单位 计算 中的 dob | 更新日期: 2023-09-27 17:58:30
private void button1_Click(object sender, EventArgs e)
{
DateTime dob = new DateTime();
textBox1.Text = dob.ToString();
int age;
age = Convert.ToInt32(textbox2.Text);
age = DateTime.Now.Year - dob.Year;
if (DateTime.Now.DayOfYear < dob.DayOfYear)
age = age - 1;
}
如何从dob中计算年龄。这是我的表格1.cs.有什么想法请
DateTime today = DateTime.Today;
int age = today.Year - bday.Year;
if (bday > today.AddYears(-age))
age--;
您可以使用TimeSpan计算它,比如:
DateTime dob = .....
DateTime Today = DateTime.Now;
TimeSpan ts = Today - dob;
DateTime Age = DateTime.MinValue + ts;
// note: MinValue is 1/1/1 so we have to subtract...
int Years = Age.Year - 1;
int Months = Age.Month - 1;
int Days = Age.Day - 1;
来源:http://forums.asp.net/t/1289294.aspx/1
[更新]:要计算闰年,请使用365.242而不是365。我相信你应该一直干到2799年。
DateTime有一个运算符重载,当您使用减法运算符时,您会得到一个TimeSpan实例。
所以你只需要做:
DateTime dob = ..
TimeSpan tm = DateTime.Now - dob;
int years = ((tm.Days)/365);
理想情况下,您的代码应该是这样的:
private void button1_Click(object sender, EventArgs e)
{
DateTime dob = //get this some somewhere..
textBox1.Text = dob.ToString();
TimeSpan tm = (DateTime.Now - dob);
int age = (tm.Days/365) ;
}
TimeSpan结构表示一个时间间隔,它具有Days
、Hours
、Seconds
等属性,因此如果需要,可以使用它们。