0

I have to write a program that reads birthday date from the console (in the format MM.DD.YYYY) and prints current age and age in 10 years.

This is one of my first codes and in my opinion it looks too lame. I believe there is a better way to write this, so I would like to ask you for suggestions on how to optimize the code.

using System;

namespace Age
{
    class Age
    {
        static void Main()
        {
            string birthDayAsk;
            Console.WriteLine("Date format: MM.DD.YYYY");
            birthDayAsk = Console.ReadLine();

            DateTime birthday = DateTime.Parse(birthDayAsk);
            DateTime today = DateTime.Today;

            int age = today.Year - birthday.Year;

            if ((birthday.Month > today.Month) || ((birthday.Month == today.Month) && (birthday.Day > today.Day)))
            {
                age = age - 1;
                Console.WriteLine(age);
            }
            else
            {
                Console.WriteLine(age);
            }
            Console.WriteLine(age + 10);
        }
    }
}
Dalija Prasnikar
  • 27,212
  • 44
  • 82
  • 159
  • 2
    Possible duplicate of [Date Difference in Years C#](http://stackoverflow.com/questions/4127363/date-difference-in-years-c-sharp) – Wobbles Apr 03 '16 at 13:09
  • `&& (birthday.Day > today.Day)` will return the wrong value if today is my birthday. – stuartd Apr 03 '16 at 13:24
  • I think you code is fine. Using other methods may not work because there are a different number of days in each month. The Month() method automatically accounts for the different number of days in each month. – jdweng Apr 03 '16 at 13:25

1 Answers1

0

I think its best to use TimeSpan to calculate difference between two dates Determining the Span Between Two Dates

Also to add the years do age.AddYears(10);

Eminem
  • 7,206
  • 15
  • 53
  • 95