3

So I used a solution found on a question from a different user here, link: How do I calculate someone's age in C#?, where the DOB was hardcoded, I added the code to take in a user input from the console to then calculate the age, however I don't know why the if statement produces a correct result, without it, it calculates the age you'll be that year, not your actual age.

var today = DateTime.Today;
Console.WriteLine("Type in your D.O.B in DD-MM-YYYY format:");
var Bday = Console.ReadLine();
var myDate = Convert.ToDateTime(Bday);
var age = today.Year - myDate.Year;
if (myDate.Date > today.AddYears(-age)) age--;
Console.WriteLine($"You are {age} years old");
Console.ReadLine();

Any help will be greatly appreciated!

Jakob Busk Sørensen
  • 5,599
  • 7
  • 44
  • 96
Ilhan
  • 33
  • 4

1 Answers1

5

You are asking about how this line works:

if (myDate.Date > today.AddYears(-age)) age--;

The number of years has been calculated by subtracting the year from the DOB from the year now. For example, if your DOB was 15/05/1979 and now is 2020 this would give:

age = 2020 - 1979 = 41

However, if this person's DOB was after today, they would not be 41 yet, they would still be 40.

In the case of the if statement, if the date of their birth (the month and day) is after today, one year is subtracted from age to give the correct age (which would be 40 in my example).

The logic is not as concise as it could be, but essentially it says:

  • Take the calculated age in years from today's date (example: 15/05/1979 = 41 years, 12/01/2020 - 41 years = 12/01/1979)
  • Is the DOB after this value? (is 15/05/1979 AFTER 12/01/1979)
  • If yes, subtract 1 from age (example: 41 - 1 = 40 years)
Martin
  • 16,093
  • 1
  • 29
  • 48
  • I think you mean "if the date of their birth (the month and day)". – juharr Jan 12 '20 at 21:50
  • @juharr I did mean that, thank you. Will correct it now – Martin Jan 12 '20 at 22:59
  • 1
    One important thing about doing exactly like that (subtracting age from current year), instead of doing simpler comparison like: "if (bday.AddYears(age) > now) age--;" is that it would circumvent leap year problem. There's a comment by Mike Polen in the initial discussion regarding this. – Alexander Goldabin Jan 13 '20 at 05:50