Skip to content

Instantly share code, notes, and snippets.

@jonathanbell
Last active March 17, 2023 23:06
Show Gist options
  • Save jonathanbell/a8f1308788cc1257649374409f142e1d to your computer and use it in GitHub Desktop.
Save jonathanbell/a8f1308788cc1257649374409f142e1d to your computer and use it in GitHub Desktop.
March 17 2023 - Compare two dates in VBA

Compare two dates in VBA

Simple example showing how to compare two dates by first converting them to epoch Unix timestamps.

Option Explicit
'Compares `leftDate` (first param) to `rightDate` (second param).
'Returns true if leftDate is LESS than (earlier in time) than
'rightDate, otherwise false. HANDLES ONLY DATES IN "AD" (no dates
'in "BC" format are valid. :(
'
'@param String leftDate
'@param String rightDate
'@returns Bool
' True if first date is earlier than second date, otherwise false.
Public Function dateDifference(leftDate As Date, rightDate As Date) As Boolean
Dim lDateUnix As LongLong
Dim rDateUnix As LongLong
lDateUnix = DateDiff("s", "1/1/0001 00:00:00", leftDate)
rDateUnix = DateDiff("s", "1/1/0001 00:00:00", rightDate)
If lDateUnix < rDateUnix Then
dateDifference = True
Exit Function
End If
dateDifference = False
End Function
Sub dateExamples()
Debug.Print dateDifference("10/10/2010", "11/11/2010") ' True
Debug.Print dateDifference("10/10/2010", "10/10/2010") ' False
Debug.Print dateDifference("13/01/2021", "01/13/2021") ' <--- unexpected results mixing TWO date formats!! Are these the same day? Who knows!? Booo...
Debug.Print dateDifference("5/2/1751", "5/3/1751") ' True
Debug.Print dateDifference("1999-11-01", "01/13/2001") ' Mixing formats (again). When it comes to dates, VBA is too permissive with these kinds of things!
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment