views:

94

answers:

3
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?

+8  A: 

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
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
+3  A: 

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
+1  A: 

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