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);
        }
    }
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
VaVa
  • 410
  • 2
  • 14
  • 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). – Tim Schmelter Nov 26 '15 at 14:43

2 Answers2

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.

Perfect28
  • 11,089
  • 3
  • 25
  • 45
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#

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364