Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 885
Darthg8r Avatar asked Aug 23 '10 20:08

Darthg8r


People also ask

How do I parse a date in a specific format?

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.

What is SimpleDateFormat?

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.

What does SimpleDateFormat parse do?

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.


2 Answers

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.

like image 97
Anthony Pegram Avatar answered Oct 06 '22 00:10

Anthony Pegram


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.

like image 34
James Curran Avatar answered Oct 05 '22 22:10

James Curran