Search code examples
c#visual-studio-2015string-to-datetime

Days on earth Calculator in C#


I've been trying to create a Days on Earth Calculator in C#, where the user can input their birthdate in MM/DD/YYYY format and find out how long they've been on this earth(in days). I already checked out a similar question that someone posted 2 years ago titled "How many days user has been alive calculator". But my issue lies within a format exception. Here is what I tried to do (I'm very new at this):

Console.WriteLine("Welcome to the Days on Earth Finder!" +
"\nPlease input your birthday(MM/DD/YYY):");
Console.ReadLine();

//string myBirthday = Console.ReadLine();
//DateTime mB = Convert.ToDateTime(myBirthday);
//DateTime myBirthday = DateTime.Parse(Console.ReadLine());
string myBirthday = Console.ReadLine();
DateTime mB = DateTime.Parse(myBirthday); //This line is where the error occurs
TimeSpan myAge = DateTime.Now.Subtract(mB);

Console.WriteLine("You are " + myAge.TotalDays + " days old!");
Console.ReadLine();

I left my previous attempts commented out if it helps. The error that comes up is as follows:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: String was not recognized as a valid DateTime.

Although when I give it a string literal it works, for example "8/10/1995".

DateTime myBirthday = DateTime.Parse("8/10/1995");
TimeSpan myAge = DateTime.Now.Subtract(myBirthday);
Console.WriteLine("You are " + myAge.TotalDays + " days old!");
Console.ReadLine();

Also I'm using Visual Studio 2015 Community RC if that helps.


Solution

  • You coded it to read the input two times and the second time is when you use the input as the date but then you are probably pressing enter (which is not a date) and it gives FormatException.

    You should remove the first ReadLine().

    Console.WriteLine("Welcome to the Days on Earth Finder!" +
    "\nPlease input your birthday(MM/DD/YYY):");
    //Console.ReadLine();
    
    //string myBirthday = Console.ReadLine();
    //DateTime mB = Convert.ToDateTime(myBirthday);
    //DateTime myBirthday = DateTime.Parse(Console.ReadLine());
    string myBirthday = Console.ReadLine();
    DateTime mB = DateTime.Parse(myBirthday);
    //This line is where the error occurs
    TimeSpan myAge = DateTime.Now.Subtract(mB);
    
    Console.WriteLine("You are " + myAge.TotalDays + " days old!");
    Console.ReadLine();