Martin Dimitrov
Martin Dimitrov

Reputation: 359

String was not in a correct format when parsed with DateTime.ParseExact

When I try to parse this string into a date:

1.05.2016

With this code:

var startDate = DateTime.ParseExact(Console.ReadLine(),
              "dd.m.yyyy", CultureInfo.InvariantCulture);

An error occurs:

Unhandled Exception: System.FormatException: String was not recognized as a valid DateTime.
   at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
   at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)
   at _09.Holidays_Between_Two_Dates.Program.Main(String[] args) in C:\Users\martin\documents\visual studio 2015\Projects\Methods. Debugging - Troubleshooting Code\09. Holidays Between Two Dates\09. Holidays Between Two Dates.cs:line 15

Can someone help? Thanks in advance.

Upvotes: 1

Views: 1547

Answers (3)

J. Tuc
J. Tuc

Reputation: 424

"M" stands for months and "m" stands for minutes. Make sure that you use correct one:

var startDate = DateTime.ParseExact(Console.ReadLine(),
             "dd.M.yyyy", CultureInfo.InvariantCulture);

Upvotes: 2

Neil Humby
Neil Humby

Reputation: 273

Can you double-check your input from the Console.Readline()? Perhaps it contains the carriage return or some other illegal characters? I ran the following in LinqPad:

DateTime.ParseExact("1.05.2016","d.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture).Dump();

And it returned "01/05/2016 00:00:00".

Upvotes: 0

Mostafiz
Mostafiz

Reputation: 7352

Correct the format because the input datetime format and provided format must match

for your input 1.05.2016 you can use

var startDate = DateTime.ParseExact(Console.ReadLine(),
              "d.MM.yyyy", CultureInfo.InvariantCulture);

but date will be not always single digit, so better to use double digit 01.05.2016 and

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

Upvotes: 1

Related Questions