0

I'm writing a small console program that calculates your age and I will add some other things later, but the problem is that this code does not calculates the age properly, it just substracts actualYear - birthYear, but if you did not had your birthday yet it displays a wrong age, how can I make this sum all the days and months that i have? I tried a lot of things and didn't work :(

Is there any way to do this using an if statement?

using System;
using System.Collections.Generic;
using System.Text;

namespace para_joel
{
    public class Person
    {
        public string name;
        public string surname;

        public int birthDay;
        public int birthMonth;
        public int birthYear;

        public int Age()
        {
            int actualYear = DateTime.Now.Year;
            int actualMonth = DateTime.Now.Month;
            int actualDay = DateTime.Now.Day;

            return actualYear - birthYear;
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • I bet that if you open this question on a computer (not a phone), one of the suggestions on the right side has to do with calculating an age with C#. Google and/or Bing will get you there too – Flydog57 Oct 01 '19 at 02:53
  • One of the 63 answers should help you – TheGeneral Oct 01 '19 at 03:08
  • Those don't really solve their problem though. Their issue is that they're storing the birthday as three separate numbers. They need to first convert those into a DateTime and then follow the link. – smithereens Oct 01 '19 at 03:21
  • 1
    Possible duplicate of [How do I calculate someone's age in C#?](https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c) – Exar666Kun Oct 01 '19 at 05:47

1 Answers1

-1

You need to convert your three int properties from Person into a Datetime with something like this:

DateTime birthday = new DateTime(birthYear, birthMonth, birthDay);

Then you need to convert today's date into a datetime (not how i'd do it, but using your variables):

DateTime today = new DateTime(actualYear, actualMonth, actualDay);

Then you need to subtract the two:

var age = today - birthday;

this will return days, so you'll want to divide by 365 to get years in age and you can do rounding as needed once you get that far.

smithereens
  • 56
  • 10