Calculate age from date of birth [closed]

0

Create a program where you can enter your name and date of birth. You should then click on a button that should display a message containing your age.

    
asked by anonymous 08.10.2016 / 16:14

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 current day, then subtract one 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 is before the day of birth = > 20 - 1 = 19 years

The best way to do this is what I found ( link ):

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--;
    
08.10.2016 / 17:18