9
DateTime dt = DateTime.ParseExact("1122010", "Mddyyyy", System.Globalization.CultureInfo.CurrentCulture);

Throwing this exception: String was not recognized as a valid DateTime.

I'm sure it's the lack of a leading 0 in the month. What's the correct format string?

Dan Esparza
  • 28,047
  • 29
  • 99
  • 127
Darthg8r
  • 12,377
  • 15
  • 63
  • 100
  • Your code sample is probably to demonstrate the type of string that you are parsing. But if you really are defining your code this way, then stop doing that :) Use the constructors/methods of `DateTime` that allow you to specify the date explicitly. – Merlyn Morgan-Graham Aug 23 '10 at 20:29
  • @Merlyn, I assume he's getting the data from an external source such as a flat file, service, etc. I don't think this will be hardcoded. – Anthony Pegram Aug 23 '10 at 20:33
  • Yes, it's from a fixed length file. It would be dumb to parseexact a hard coded string get a datetime instance. – Darthg8r Aug 27 '10 at 02:55
  • I connected to .NET Framework Team about this issue, and [here their response](http://stackoverflow.com/a/26778076/447156). – Soner Gönül Nov 27 '14 at 07:10

3 Answers3

12

I suggest using the format "MMddyyyy" and ensuring your input parameter has at least 8 characters. Example:

DateTime dt = DateTime.ParseExact("1122010".PadLeft(8, '0'), "MMddyyyy", System.Globalization.CultureInfo.CurrentCulture);

If you are using a data source with the leading 0 missing for the month, this will add it where required.

Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
  • This is a special case scenario, and probably the only possible solution. MSDN: If you do not use date or time separators in a custom format pattern, use the invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify hours in the pattern, specify the wider form, "HH", instead of the narrower form, "H". – chilltemp Aug 23 '10 at 20:44
  • Note that the padding only works for months lower than number 10. If you try the same with daynumber less than 10, odd dates may show up. Or even both: `'112010' -> '00112010'` I agree on ensuring the eight characters though. – Caramiriel Mar 05 '13 at 11:29
4

The problem is that you are not giving ParseExact enough information to work with.

"M" means a 1 or 2 digit month. But your string starts with "1122". Is that January 12th or November 22nd?

The only solution, as Anthony shows, is to pad with a 0 when needed.

James Curran
  • 101,701
  • 37
  • 181
  • 258
1

The single "M" format string is unacceptable because not all months can be uniquely represented with a single digit or character. As previously suggested, you will have to use "MMddyyyy" and pad the left string when necessary.

Judicium
  • 56
  • 4