C# DateTime.ParseExact

C#ParsingDatetime

C# Problem Overview


I have a tab delimited file which is being parsed and then inserted into a database. When I run into the date column, I have trouble parsing it.

The code I have is:

var insert = DateTime.ParseExact(line[i], "d/M/yyyy h:mm", CultureInfo.InvariantCulture);

The string in line[i] is in the formats: 7/7/2011 10:48 , 10/20/2011 6:27

The exception I get says

> The DateTime represented by the string is not supported in calendar > System.Globalization.GregorianCalendar.

C# Solutions


Solution 1 - C#

Your format string is wrong. Change it to

insert = DateTime.ParseExact(line[i], "M/d/yyyy hh:mm", CultureInfo.InvariantCulture);

Solution 2 - C#

That's because you have the Date in American format in line[i] and UK format in the FormatString.

11/20/2011
M / d/yyyy

I'm guessing you might need to change the FormatString to:

"M/d/yyyy h:mm"

Solution 3 - C#

It's probably the same problem with cultures as presented in this related SO-thread: https://stackoverflow.com/questions/1368636/why-cant-datetime-parseexact-parse-9-1-2009-using-m-d-yyyy

You already specified the culture, so try escaping the slashes.

Solution 4 - C#

try this

var  insert = DateTime.ParseExact(line[i], "M/d/yyyy h:mm", CultureInfo.InvariantCulture);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonathanView Question on Stackoverflow
Solution 1 - C#FischermaenView Answer on Stackoverflow
Solution 2 - C#DaveShawView Answer on Stackoverflow
Solution 3 - C#PieterView Answer on Stackoverflow
Solution 4 - C#Glory RajView Answer on Stackoverflow