DATE AND TIMESPAN OPERATIONS

The Date data type is fundamentally different from other data types. When you perform an operation on most data types, you get a result that has the same data type or that is at least of some compatible data type. For example, if you subtract two Integer variables, the result is an Integer. If you divide two Integers using the / operator, the result is a Double. That’s not another Integer, but it is a compatible numeric data type used because an Integer cannot always hold the result of a division.

If you subtract two Date variables, however, the result is not a Date. For example, what’s August 7 minus July 20? It doesn’t make sense to think of the result as a Date. Instead, Visual Basic defines the difference between two Dates as a TimeSpan. A TimeSpan measures the elapsed time between two Dates. In this example, August 7 minus July 20 is 18 days. (And yes, TimeSpans know all about leap years.)

The following equations define the arithmetic of Dates and TimeSpans:

  • Date − Date = TimeSpan
  • Date + TimeSpan = Date
  • TimeSpan + TimeSpan = TimeSpan
  • TimeSpan − TimeSpan = TimeSpan

The TimeSpan class also defines unary negation (ts2 = -ts1), but other operations (such as multiplying a TimeSpan by a number) are not defined. However, in some cases, you can still perform the calculation if you must.

Example program MultiplyTimeSpan, which is available for download on the book’s website, uses the following statement to make the TimeSpan ts2 equal to 12 times the duration ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.