Link to home
Start Free TrialLog in
Avatar of Mike_Stevens
Mike_StevensFlag for United States of America

asked on

Validate time value using vb.net

I am looking for a method to validate a time value to make sure it is a valid time.   I have found several examples but i need to validate both the 24 hour format (hh:mm) or (h:mm am/pm) format.   I cannot find any examples of how to do both.   I am using vb.net with 3.5 version framework.

I am hoping somone can help.  Thanks
Avatar of Stephen Manderson
Stephen Manderson
Flag of United Kingdom of Great Britain and Northern Ireland image

Hi there the below function should do the trick
    Public Function IsValidTime(ByVal TheTime As String) As Boolean
        ' Format 1 validates the time against the 12 hour format
        Dim Format1 As String = "^ *(1[0-2]|[1-9]):[0-5][0-9] *(a|p|A|P)(m|M) *$"
        Dim TryValidateFormat1 As New System.Text.RegularExpressions.Regex(Format1)
        ' Format 2 validates the 24 hour format
        Dim Format2 As String = "^[0-2][0-3][:][0-5][0-9]$"
        Dim TryValidateFormat2 As New System.Text.RegularExpressions.Regex(Format2)
 
        Return TryValidateFormat1.IsMatch(TheTime) Or TryValidateFormat2.IsMatch(TheTime)
 
    End Function

Open in new window

Tested against the following

Is 11:00 valid : ? True
Is 1:00 PM valid : ? True
Is 11:61 valid : ? False
Is 13:00 PM valid : ? False
Is 143:00 valid : ? False
Is 1:00 ZM valid : ? False
Is 23:60 valid : ? False

Regards
Steve
Avatar of Mike_Stevens

ASKER

I tried entering 16:22 (4:22 pm) and false is returned.  
ASKER CERTIFIED SOLUTION
Avatar of Stephen Manderson
Stephen Manderson
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Awesome...that works....thanks
Avatar of Mike Tomlinson
Why not just use DateTime.TryParse()?....
        Dim dt As DateTime
        Dim strTime As String
 
        strTime = "16:22"
        If DateTime.TryParse(strTime, dt) Then
            Debug.Print(dt.ToString("t"))
        Else
            Debug.Print("Failed")
        End If
 
        strTime = "4:22 pm"
        If DateTime.TryParse(strTime, dt) Then
            Debug.Print(dt.ToString("t"))
        Else
            Debug.Print("Failed")
        End If

Open in new window