C# DateTime.ParseExact
Asked Answered
C

5

72

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.

Contextual answered 6/12, 2011 at 14:34 Comment(2)
This works for me, without change for the date string provided.Polyanthus
It's work for me, Maybe a string in line list has incorrect format.Roaring
O
121

Your format string is wrong. Change it to

insert = DateTime.ParseExact(line[i], "M/d/yyyy hh:mm", CultureInfo.InvariantCulture);
Osculate answered 6/12, 2011 at 14:36 Comment(5)
don't you mean M/d/yyyy or d/M/yyyy He doesn't have any leading zeros on his exampleDetta
@Sign: You're right! I've changed my answer. Thanks for mentioning that.Osculate
wow I can't believe I missed that. Turns out the date was in M/d/yyyy instead of d/M/yyyy. I didn't notice because the first few dates were in early days of the month.Contextual
@Jonathan: I only found that, because you had a date like "10/20/2011" in your first version of your question. Later you changed that to "7/7/2011 10:48". ;-)Osculate
Oh LOL, I changed it to show that the format didn't have leading zeros. I didn't even notice the date I used first.Contextual
P
4

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"
Pattern answered 6/12, 2011 at 14:38 Comment(0)
S
1

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.

Suu answered 6/12, 2011 at 14:37 Comment(0)
M
1

try this

var  insert = DateTime.ParseExact(line[i], "M/d/yyyy h:mm", CultureInfo.InvariantCulture);
Means answered 6/12, 2011 at 14:38 Comment(0)
F
0
var insert = DateTime.ParseExact(line[i].toString(), "d/M/yyyy h:mm", CultureInfo.InvariantCulture);
Footbridge answered 3/7 at 15:49 Comment(1)
don't forget the "toString()" methodFootbridge

© 2022 - 2024 — McMap. All rights reserved.