Calculate age from date of birth

Asked

Viewed 8,384 times

0

Create a program where the user can enter his name and date of birth. Then click on a button that should display a message containing your age.

  • 1

    What did you do? What’s the question?

  • 1

    I did the graphical part only, put a Textbox, two Label "name" and "date of birth", a Button "Calculate Age", and a Datetimerpicker. Only that. My doubts are the commands to calculate the display age on the screen

  • You have to enter the date (in your case choose) and at the time of calculation inform the number of years, by the current date?

  • 1

    Yeah, yeah, that’s right!

  • change the title of your question, asked about years calculation of a date in C#

  • put the half response redirected with the comments.

  • 1

    and to appear in message format on the screen I put "Messagebox.Show("{0}");" that’s it?

  • i did the editing.

Show 3 more comments

1 answer

7

We have to consider that age is determined from the difference in years, and if the day of birth is greater than the present day, then subtract a unit:

Example: Birth on 10/01/1980

  • if today is 10/01/2000 => 2000 - 1980 = 20 years
  • if today is 09/01/2000 => 2000 - 1980 = 20, but we have to subtract 1 because the day before birth => 20 - 1 = 19 years

The best way to do it I could think of (https://stackoverflow.com/a/1404/195417):

var birthdate = new DateTime(1980, 1, 10);
var today = new DateTime(2000, 1, 9);
var age = today.Year - birthdate.Year;
if (birthdate > today.AddYears(-age)) age--;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.