how can i calculate age by datetimepicker [duplicate]
Possible Duplicate:
How do I calculate someone’s age
How can i calculate age using datetimep开发者_运维问答icker 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.
Assuming that the DateTimePicker is called dtpBirthday:
int age = DateTime.Now.Year - dtpBirthday.Value.Year - (DateTime.Now.DayOfYear < dtpBirthday.Value.DayOfYear ? 1 : 0);
精彩评论