how can i calculate age by datetimepicker

Possible Duplicate:
How do I calculate someone's age

How can i calculate age using datetimepicker in c#?


Strictly speaking,

TimeSpan age = DateTime.Now - dateTimePicker.Value;

However, figuring out someone's "age" is only slightly more complicated.

int years = DateTime.Now.Year - dateTimePicker.Value.Year;

if(dateTimePicker.Value.AddYears(years) > DateTime.Now) years--;

Because years vary in length you'll have to do this rather than relying on a structure like the TimeSpan that represents a specific amount of time (the same is true for figuring out how many "months" are between two dates, since months vary in length from 28-31 days).

The last line of code is there to account for the person's birthday not yet taking place this year.


假设DateTimePicker被称为dtpBirthday:

int age = DateTime.Now.Year - dtpBirthday.Value.Year - (DateTime.Now.DayOfYear < dtpBirthday.Value.DayOfYear ? 1 : 0);
链接地址: http://www.djcxy.com/p/54356.html

上一篇: 计算年龄的最简单和最正确的方法是什么?

下一篇: 我怎么能通过datetimepicker计算年龄