Karen
Karen

Reputation: 2435

DateTime.ParseExact formats question

I have datetime strings that look can like any the following:

"1 13 2009 2300", "1 14 2009 0", "1 14 2009 100"

that I need to parse into a DateTime.

I have tried:

string[] sExpectedFormats = {"M d yyyy Hmm", "M d yyyy hmm", "M d yyyy 0"};
DateTime dtReportDateTime = DateTime.ParseExact(sReportDateTime, 
 sExpectedFormats, 
 System.Globalization.CultureInfo.InvariantCulture,
 System.Globalization.DateTimeStyles.None);

but it fails on the third one "1 14 2009 100". I am not sure what format to use for that?

To clarify, I get this data in a feed as a date part "1 14" and a time part "100", so am concatenating it so I can parse into a DateTime.

Thanks

Upvotes: 3

Views: 702

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1502046

I suspect that it's interpreting the "100" as "10" followed by "0" - i.e. parse the H or h as "10" and then fail to find two digits for the minutes.

Frankly I'd be tempted to manually reformat the string before parsing so that it always ends in 4 digits instead of 3. Reluctant as I am to recommend them usually, this does sound like a job for regular expressions :)

Just as an aside, I'm not sure why you've got both the "H" and "h" formats - it's never going to match the second format, because anything valid for the second would have been valid for the first.

If you fix up the string beforehand as I've suggested, you can then just use

{"M d yyyy HHmm", "M d yyyy 0"}

Upvotes: 6

Webleeuw
Webleeuw

Reputation: 7282

I think it fails because "hmm" = "100" is ambiguous between 1:00 AM or PM. Maybe you should stick to "Hmm" or use "hmm tt" = "100 AM" format.

Edit: tried and failed. What Jon said in his answer and my comment is true.

Upvotes: 0

Related Questions