3

Possible Duplicate:
How do I calculate someone’s age

How can i calculate age using datetimepicker in c#?

Community
  • 1
  • 1
Malou Go
  • 57
  • 2
  • 3
  • 8

2 Answers2

7

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.

Adam Robinson
  • 182,639
  • 35
  • 285
  • 343
  • int years = DateTime.Now.Year - dateTimePicker.Value.Year; if(dateTimePicker.Value.AddYears(years) > DateTime.Now) years--; >> why is that when i added that code in datetimepicker.... the age doesnt appear? – Malou Go Feb 10 '10 at 15:05
  • @malou17: Adding that code isn't going to make the age appear, it just calculates it and puts it in a variable for you. How do you want it to appear? – Adam Robinson Feb 10 '10 at 15:21
  • Pretty sleek logic, tthe datepicker's ValueChanged is where you can place the code. – Manny265 Feb 09 '17 at 01:32
0

Assuming that the DateTimePicker is called dtpBirthday:

int age = DateTime.Now.Year - dtpBirthday.Value.Year - (DateTime.Now.DayOfYear < dtpBirthday.Value.DayOfYear ? 1 : 0);
Jeff Hornby
  • 12,948
  • 4
  • 40
  • 61
  • This would not account for a birthday taking place later in the current month. For example, if my birthday happened to be February 24, 1901, then this code would say I'm already 109 when I'm only a spry 108. – Adam Robinson Feb 10 '10 at 14:56