Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i calculate age by datetimepicker [duplicate]

Tags:

c#

Possible Duplicate:
How do I calculate someone’s age

How can i calculate age using datetimepicker in c#?

like image 401
Malou Go Avatar asked Dec 02 '25 21:12

Malou Go


1 Answers

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.

like image 124
Adam Robinson Avatar answered Dec 04 '25 11:12

Adam Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!