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.

Morvael
  • 3,478
  • 3
  • 36
  • 53
Jonathan
  • 1,923
  • 2
  • 16
  • 34

4 Answers4

120

Your format string is wrong. Change it to

insert = DateTime.ParseExact(line[i], "M/d/yyyy hh:mm", CultureInfo.InvariantCulture);
Fischermaen
  • 12,238
  • 2
  • 39
  • 56
  • 1
    don't you mean `M/d/yyyy` or `d/M/yyyy` He doesn't have any leading zeros on his example – Sign Dec 06 '11 at 14:41
  • 1
    @Sign: You're right! I've changed my answer. Thanks for mentioning that. – Fischermaen Dec 06 '11 at 14:42
  • 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. – Jonathan Dec 06 '11 at 14:57
  • 3
    @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". ;-) – Fischermaen Dec 06 '11 at 15:01
  • 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. – Jonathan Dec 06 '11 at 21:46
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"
DaveShaw
  • 52,123
  • 16
  • 112
  • 141
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.

Community
  • 1
  • 1
Pieter
  • 3,339
  • 5
  • 30
  • 63
1

try this

var  insert = DateTime.ParseExact(line[i], "M/d/yyyy h:mm", CultureInfo.InvariantCulture);
Glory Raj
  • 17,397
  • 27
  • 100
  • 203