Microsoft KB Archive/194894

= PRB: Date Comparison Can fail Using Arithmetic Operators =

Article ID: 194894

Article Last Modified on 6/29/2004

-

APPLIES TO


 * Microsoft Visual Basic 5.0 Learning Edition
 * Microsoft Visual Basic 6.0 Learning Edition
 * Microsoft Visual Basic 5.0 Professional Edition
 * Microsoft Visual Basic 6.0 Professional Edition
 * Microsoft Visual Basic 5.0 Enterprise Edition
 * Microsoft Visual Basic 6.0 Enterprise Edition
 * Microsoft Visual Basic for Applications 5.0
 * Microsoft Visual Basic 4.0 Standard Edition
 * Microsoft Visual Basic 4.0 Professional Edition
 * Microsoft Visual Basic 4.0 Enterprise Edition

-



This article was previously published under Q194894



SYMPTOMS
Comparing two apparently identical dates using the standard comparison operators produces anomalous results.



CAUSE
The Visual Basic Date data type is stored internally as a Double (64 bit floating point). Performing operations on Date variables is subject to the same rounding problems as any other floating point value. This is true even if most of the intrinsic functions, such as DateAdd, are used.



RESOLUTION

 * 1) Use the DateDiff intrinsic function to compare date and time values. DateDiff rounds the input values to the specified tolerance, eliminating floating point errors.
 * 2) Take the difference between two variables of type Date and compare the absolute value of the result to a tolerance value such as 10E-11. If the difference is less than the tolerance, the values may be considered identical.



STATUS
This behavior is by design.



Steps to Reproduce Behavior
 Create a Standard EXE project in Visual Basic. Form1 is created by default.  Add the following code to the General Declarations section of Form1: Option Explicit

Private Sub Form_Load Dim Date1 As Date Dim Date2 As Date Dim Date3 As Date Dim Date4 As Date Me.Width = 6500 Me.Height = 3000 Me.Show Date1 = #10/21/1998 8:00:00 AM# Date2 = #10/21/1998 8:20:00 AM# Date3 = DateAdd("n", 20#, Date1) Date4 = Date1 + TimeSerial(0, 20, 0) Print "The results are visually identical..." Print Print "Date2 = "; Date2 Print "Date3 = "; Date3 Print "Date4 = "; Date4 Print Print "but the actual values are not" Print Print Tab(20), "=", "DateDiff", "Actual Difference" Print "Date2 = Date3?", Date2 = Date3, Print DateDiff("s", Date2, Date3), Date2 - Date3 Print "Date2 = Date4?", Date2 = Date4, Print DateDiff("s", Date2, Date4), Date2 - Date4 Print "Date3 = Date4?", Date3 = Date4, Print DateDiff("s", Date3, Date4), Date3 - Date4 End Sub

 Run the application and examine the results on the form.

