VB Quark #6: Date operators

The DateTime structure in .NET includes custom operators for Date comparisons such as less than, greater than, equal and not equal; but did you know it also includes addition and subtraction operators ?  There’s two subtraction operators and one addition operator defined inside DateTime:

  • date = date – timespan
  • timespan = date – date
  • date = date + timespan

Those three cases should all seem relatively obvious, such as adding or subtracting an hour from a date, or calculating how many minutes between two dates etc…

BUT, did you know VB also defines another case where you can add two dates, eg:

     Dim result = Date1 + Date2

Now if you guessed that the type of result is String, then congratulations !! Note: this operator resolution is only valid with Option Strict Off

Obviously adding two dates can’t give a valid date or timespan, so the only real options are to return a string concatenation of the date or throw an error. There are a couple of fringe cases where, depending on your system locale, the resultant string can indeed be parsed back into a date, eg:

      Dim dt1 = #1:00:00 PM#
dt2 = Now.Date
Dim dtResult As Date = dt1 + dt2

But that really is a fringe case, and would depend on the system locale formatting.

I think it’s probably fair to say this case is a quirk of a quark, probably introduced as partial legacy. I honestly can’t see any usefulness of the addition operator between two dates that returns a string. If the intent was some legacy support, it might have made sense to return a date if one of the dates was date zero with time information, but the concatenation of the date strings doesn’t seem to reliably serve any purpose.

The good news is you can only do the string = date + date operation with Option Strict Off. Guess that’s just another reason to turn Option Strict On  Winking smile