[c#] C# DateTime.ParseExact

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.

This question is related to c# parsing datetime

The answer is


Your format string is wrong. Change it to

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

try this

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

It's probably the same problem with cultures as presented in this related SO-thread: Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

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


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"

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to parsing

Got a NumberFormatException while trying to parse a text file for objects Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Python/Json:Expecting property name enclosed in double quotes Correctly Parsing JSON in Swift 3 How to get response as String using retrofit without using GSON or any other library in android UIButton action in table view cell "Expected BEGIN_OBJECT but was STRING at line 1 column 1" How to convert an XML file to nice pandas dataframe? How to extract multiple JSON objects from one file? How to sum digits of an integer in java?

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?