tags:

views:

162

answers:

2

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

+6  A: 

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"}
Jon Skeet
I add the "h" format in some attempt to get to parse the one that is failing. I will try to reformat the time part so it's always "HHMM"
Karen
ok, managed to convert the timepart into a h:mm format, so I can use the "M d yyyy H:m" in my parse exact and all works great.
Karen
A: 

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.

Webleeuw
It's not the ambiguity of the am/pm - it's the ambiguity of where the hours stops and the minutes starts. Otherwise it would fail for 1100 as well, but that actually works...
Jon Skeet