Darthg8r
Darthg8r

Reputation: 12675

Parse Simple DateTime

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?

Upvotes: 9

Views: 844

Answers (3)

Judicium
Judicium

Reputation: 66

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.

Upvotes: 1

James Curran
James Curran

Reputation: 103485

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.

Upvotes: 4

Anthony Pegram
Anthony Pegram

Reputation: 126804

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.

Upvotes: 12

Related Questions