Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.ParseExact formats question

Tags:

c#

datetime

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

like image 316
Karen Avatar asked Jun 09 '26 14:06

Karen


1 Answers

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"}
like image 192
Jon Skeet Avatar answered Jun 12 '26 04:06

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!