How to calculate age in years from dob in c#
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 10 11 | 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; } |
如何从出生日期算起年龄。这是我的表格1.cs。有什么想法吗?
1 2 3 4 5 6 | DateTime today = DateTime.Today; int age = today.Year - bday.Year; if (bday > today.AddYears(-age)) age--; |
您可以使用以下时间跨度计算它:
1 2 3 4 5 6 7 8 9 10 | 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实例。
所以你只需要:
1 2 3 | DateTime dob = .. TimeSpan tm = DateTime.Now - dob; int years = ((tm.Days)/365); |
理想情况下,您的代码应该如下所示:
1 2 3 4 5 6 7 | 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结构代表一个时间间隔,它具有