开发者

how can i calculate age by datetimepicker [duplicate]

开发者 https://www.devze.com 2022-12-19 23:17 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: How do I calculate someone’s age
This question already has answers here: Closed 10 years ago.

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消