Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date.Parse with a custom formatter

This seems like a simple exercise, but I'll be darned if I can find an example of doing it right in MSDN or anywhere on the web.

We have data feed, a file with index values and dates (like the S&P 500, for instance). The dates are represented as YYYYMMDD. The Date.Parse() method doesn't understand this format, of course.

I wrote a simple static method on a class to parse this, not a big deal, but it irritates the engineer in me that I can't figure out how to get the IFormatProvider functionality to work. All the examples deal with the FORMATTING step, not the PARSING step.

So basically, I want to be able to say:

Dim d as DateTime = Date.Parse("20110522", New CustomFormatter())

and get the correct date value out of the Parse method.

Having implemented the IFormatProvider method on CustomFormatter, the GetFormat() method gets called with a System.Type of DateTimeFormatInfo, but I honestly have no idea what to do from there since all the example deal with formatting, not parsing. It doesn't matter if I return an object (self) or null I simply get "String was not recognized as a valid DateTime."

Any pointers appreciated. Thanks.

like image 892
user458314 Avatar asked Jun 09 '26 10:06

user458314


1 Answers

Use DateTime.ParseExact() instead; MSDN post has examples.

like image 115
Bala R Avatar answered Jun 12 '26 11:06

Bala R



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!