IsDate and IsTime functions (VB Work-A-Like)

Modified on 2021/11/27 15:09 by CaptainBoing — Categorized as: Dates, Time and Clocks, Maths, Strings

The following are two functions to validate dates and times.

Inspired by the VB functions of the same name.

Often when a user is asked to enter either, there is quite a bit of code to make sure that what they entered makes sense. These functions check both the format and values and return a boolean (actually an integer) of 0 if the string is not a Date/Time. Non zero indicates the string is valid.

Earlier versions of these functions used Regular Expressions to match the "look & feel" of time and date strings. This made things very easy but RegExps are notoriously compute-heavy. Previous versions were quite slow and had the huge code overhead of the RegExp module. If you were only using RegExps for IsDate/IsTime was difficult to justify the extra 2K of program.

The versions presented below, dispense with the RegExps. Consequently they are a bit longer than the originals (not including the RegExp module) but total code footprint is much-reduced and they are now very quick - about seven times faster.

Check the history of this article if you are curious about the versions using RegExps.

Notes IsDate:

Notes IsTime:

Syntax:
=IsTime(TimeStr$)
=IsDate(DateStr$)

Examples:
If Not IsDate(dt$) Then Exit Sub
Checkbox=IsTime(A$)

Dependencies:
IsLeapYear Function

	Function IsTime(a$) As Integer
		Local d$
		Local Integer x,z
		IsTime=0
		If Len(a$)=8 Then
			d$=Mid$(a$,3,1)
			If d$=":" Then 
				d$=Mid$(a$,6,1)
				If d$=":" Then
					'here a$=??:??:??
					For x=1 To 8
						If x=3 or x=6 Then
						Else
							z=Asc(Mid$(a$,x,1))
							If z<&h30 Or z>&h39 Then Exit Function
						EndIf
					Next
					If Val(Left$(a$,2))<24 Then
						If Val(Mid$(a$,4,2))<60 Then
							If Val(Right$(a$,2))<60 Then
								IsTime=1
							EndIf
						EndIf
					EndIf				
				EndIf
			EndIf
		EndIf
	End Function

	Function IsDate(a$) As Integer
		Local d$
		Local Integer x,z
		IsDate=0
		If Len(a$)=10 Then
			d$=Mid$(a$,3,1)
			If d$="-" Or d$="/" Then
				d$=Mid$(a$,6,1)
				If d$="-" Or d$="/" Then
					'here a$=??/??/????
					For x=1 To 10
						If x=3 Or x=6 Then
						Else
							z=Asc(Mid$(a$,x,1))
							If z<&h30 Or z>&h39 Then Exit Function
						EndIf
					Next
					x=Val(Left$(a$,2)):z=Val(Mid$(a$,4,2))
					If x<1 Then Exit Function
					Select Case z
						Case 1,3,5,7,8,10,12
							If x>31 Then Exit Function
						Case 4,6,9,11
							If x>30 Then Exit Function
						Case 2
							If x>28+IsLeapYear(Val(Right$(a$,4))) Then Exit Function
						Case Else
							Exit Function
					End Select
					IsDate=1
				EndIf
			EndIf
		EndIf
	End Function

There are several optimizations possible on the above code that have been omitted in the interests of legibility.