-2

I'm trying to figure out how to calculate the current year minus the birth year to calculate age

namespace howOldAreYou
{
    class Program
    {
        public static void Main(string[] args)
        {
            //variables

            int birthYear;
            string name;
            System.DateTime moment = new System.DateTime();
            int year = moment.Year;
            //int month = moment.Month;
            //int day = moment.Day;
            //int minute = moment.Minute;
            //int second = moment.Second;
            //int millisecond = moment.Millisecond;

            //Find out person's name
            Console.WriteLine("What is your name?");
            name = Console.ReadLine();

            //Find what year person was born
            Console.WriteLine("What year were you born, " + name + "?" );
            if (int.TryParse(Console.ReadLine(), out birthYear))
            {
                Console.WriteLine(birthYear + "! Well you must be " + (year - birthYear));
            }
            else
            {
                Console.WriteLine("Sorry that's an invalid year");
            }

        }
    }
}
Nirav Ranpara
  • 13,753
  • 3
  • 39
  • 54

1 Answers1

0

This is a strange question since to calculate age, you need to ask the user to provide the day and time as well. But I'm guessing you want to go for an "approximate age". In that case, simply use the following:

System.DateTime.Now.Year

Instead of:

new System.DateTime().Year;

The latter has no parameters provided to it, so by default it returns 1. The former returns the present year.

Sirar Salih
  • 2,514
  • 2
  • 19
  • 18
  • Date is required to calculate age. Time is not. – Matt Johnson-Pint Oct 07 '16 at 22:02
  • Well, to be precise time should be included. To be truly precise (in .NET) ticks should be included, but that may be taking it a bit too far ;-) – Sirar Salih Oct 07 '16 at 22:07
  • Nope. If you are asking for age, you're asking for "whole years completed on a calendar". The only thing time matters is in determining which day is "today", based on time zones of who's asking the question or where the target subject is located. Time of birth only matters if you want to know "how many hours/minutes/seconds/etc old is a person", which oddly is usually not what we mean when we say "age". More at http://codeofmatt.com/2014/04/09/handling-birthdays-and-other-anniversaries/ Cheers! :) – Matt Johnson-Pint Oct 07 '16 at 22:10