1

Heres the code I have so far and I'm stuck at the moment.

    static void Main(string[] args)
    {
        int age = 0;
        DateTime now = DateTime.Today;

        Console.WriteLine("What is your age?");
        age = Convert.ToInt32(Console.ReadLine());

    }
rioV8
  • 24,506
  • 3
  • 32
  • 49
Nathan
  • 21
  • 2
  • Please elaborate what's holding you back. What are you having trouble with? – Xerillio Apr 30 '21 at 22:45
  • As mentioned. State the specific issue you are having. Give a reproducible example, along with what the desired output would be. This will make it far easier for people to assist you. – Alos Apr 30 '21 at 22:46
  • 4
    it's always ambiguous what year they were born in depending on whether they have had their birthday or not this year – Keith Nicholas Apr 30 '21 at 22:46
  • 1
    @KeithNicholas not if they enter their age in milliseconds... :D – Rufus L Apr 30 '21 at 22:50
  • I think you're looking for `int yearBorn = DateTime.Now.AddYears(-age).Year;` (notice that we add the negative of their age since there is no `SubtractYears` method). But as @KeithNicholas said, if they haven't had their birthday yet you have to add one to that result. Or you could just say `Console.WriteLine($"You were born in {yearBorn} (or {yearBorn + 1} if you haven't had your birthday yet");` – Rufus L Apr 30 '21 at 22:54
  • [How do I calculate someone's age based on a DateTime type birthday?](https://stackoverflow.com/q/9/7444103) – Jimi May 01 '21 at 08:18

1 Answers1

1

An easy way to do this would to create a string variable that is a console.readline, convert the string to and int(age), and subtract age from the current year, the result of this equation will be the year they were born. However this is still not perfect as if you have not had your birthday yet it could be a year off.

String stringAge = Console.ReadLine();
int age = Convert.ToInt32(stringAge);
//year is 2021
int result = age-2021;