3

The following piece of code gives me the following error:

"Unhandled Exception: string was not recognized as a valid DateTime.

There is an unknown word starting at index 0."

How can I convert the string to DateTime properly here?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exercise
{
    class Program
    {
        static void Main(string[] args)
        {  
            Console.Write("Enter your birthday in format(dd.mm.yyyy): ");
            DateTime userBirthday = DateTime.Parse(Console.ReadLine());
            long result = DateTime.Today.Subtract(userBirthday).Ticks;
            Console.WriteLine("You are {0} years old.", new DateTime(result).Year - 1);
            Console.WriteLine("After 10 years you will be {0} years old.", new DateTime(result).AddYears(10).Year - 1);
        }
    }
}
1
  • 2
    Use DateTime.TryParse/DateTime.TryParseExact if you get user input. Apart from that, what did the user give you as input? What is your current date setting(control-panel/region and language). Commented Nov 26, 2015 at 14:43

2 Answers 2

5

You can use ParseExact to specify the date format:

DateTime userBirthday  = DateTime.ParseExact(Console.ReadLine(), "dd.MM.yyyy", CultureInfo.InvariantCulture) ; 

Or TryParseExact if you don'trust the user input:

 DateTime userBirthday ; 

 if (!DateTime.TryParseExact(Console.ReadLine(), "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out userBirthday)) 
 {
   Console.WriteLine("You cheated") ; 
   return ; 
 }

Available DateTime format can be found here.

Sign up to request clarification or add additional context in comments.

Comments

1

DateTime.Parse uses standard date and time formats of your CurrentCulture settings by default. Looks like dd.mm.yyyy is not one of them.

You can use DateTime.ParseExact or DateTime.TryParseExact methods to specifiy your format exactly.

By the way, I strongly suspect you mean MM (for months) instead of mm (for minutes).

DateTime userBirthday = DateTime.ParseExact(Console.ReadLine(), 
                                            "dd.MM.yyyy", 
                                            CultureInfo.InvariantCulture);

By the way, calculating age is difficult in programming since it depends on where you were born and where you are right now.

Check this: Calculate age in C#

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.