Date, Date?, and the ToString Method in VB.Net

I just spent the last 45 minutes frustrated as to why I was getting the following exception

Input string was not in the correct format

“Input string was not in a correct format.” and “[InvalidCastException: Conversion from string “MMMM dd, yyyy” to type ‘Integer’ is not valid.]

I kept thinking to myself, “How hard can this possibly be?!!  I’ve done this a thousand times — Why is it wanting to convert my format string into an Integer??!  AAHHH!!”.  Consulting MSDN on the matter only confirmed that I knew what I was doing with the string formatter.

What got me in the end is that it turns out I didn’t know what I was doing with my Date object.  In fact, I wasn’t dealing with a Date object at all.  I was dealing with a Date? object (that is, a Nullable(of Date)Date and Date?  are not the same. And it matters, because the ToString() method of Date has _different overloads _than the ToString() method of Date?.  Only the Date type allows you to put in a format string to fancy up how the date is displayed when it’s converted to a string.

My solution:

  1.  Wrap my Date? object instance in a CType, converting to type Date.

  2.  Call ToString() on the converted value:

    CType(someObject.dateInstance, Date).ToString("MMMM dd, yyyy")
    

Sanity… recovered.

comments powered by Disqus