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?
Instantiate the SimpleDateFormat class by passing the desired (new) format as string to its constructor. Invoke the format() method by passing the above obtained Date object as parameter.
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.
The parse() Method of SimpleDateFormat class is used to parse the text from a string to produce the Date. The method parses the text starting at the index given by a start position.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With