Valid Date

how do you verify what's in a text box is a valid date?
dblanch12Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

farsightCommented:
Here's one way.

    If DateTryParse(yourTextBox.Text) Is Nothing Then
        ... ' Text is not recognizable as date.
    Else
        ... ' We've got a valid date.
    EndIf


    Private Function DateTryParse(ByVal s As String) As Date
        Dim dt As Date = Nothing
        Try
            dt = Date.Parse(s)
        Catch ex As Exception
            ' Skip it.  dt is still Nothing.
        End Try
        Return dt
    End Function
0
GlomCommented:
Or you can do it without exception handling, because it takes a lot of time to generate an exception.

If IsDate(TextBox1.Text) Then
    '.....
End If
0
farsightCommented:
So true.

In the past, I've tried to completely avoid using Microsoft.VisualBasic namespace even in VB.NET, so that converting code to/from C# is easier.   More and more, I think just using the Microsoft.VisualBasic namespace in C# is much better.  This is a great example.  Since C# doesn't have IsDate(), it would normally have to use a solution like DateTryParse (though there are other options, too), and look how slow that is.  It would be better to just use Microsoft.VisualBasic.IsDate() from C#, and it would be speedy.

---
A quick hack of a test shows it clearly.
(This is testing actual conversion to a Date, not just checking if it is a Date, but I'd expect similar results.)
[On an old 650Mhz machine]

Good dates
Test 0 IsDate: milliseconds 0
Test 1 DateTryParse: milliseconds 70.1008
Bad dates
Test 0 IsDate: milliseconds 0
Test 1 DateTryParse: milliseconds 18116.0496

[VB.NET]
    Private Sub btnTestIsDate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTestIsDate.Click
        Dim dates As String() = New String() { _
            "1/1/2000", _
            "5/5/1990" _
            }
        Dim baddates As String() = New String() { _
            "not-a-date", _
            "nope" _
            }

        Debug.WriteLine("Good dates")
        TestIsDate(1000, dates)
        Debug.WriteLine("Bad dates")
        TestIsDate(1000, baddates)
    End Sub

    Private Sub TestIsDate(ByVal loops As Integer, ByVal dates As String())
        Dim tests As String() = New String() {"IsDate", "DateTryParse"}
        Dim dt As Date
        For test As Integer = 0 To tests.Length - 1
            Dim startTime As DateTime = Now()
            Select Case test
                Case 1
                    For i As Integer = 0 To loops - 1
                        dt = MyIsDate(dates(i Mod dates.Length))
                    Next
                Case 2
                    For i As Integer = 0 To loops - 1
                        dt = DateTryParse(dates(i Mod dates.Length))
                    Next
            End Select
            Dim stopTime As DateTime = Now()
            Dim ts As TimeSpan = stopTime.Subtract(startTime)
            Debug.WriteLine(String.Format("Test {0} {1}: milliseconds {2}", _
                test, tests(test), ts.TotalMilliseconds))
        Next
    End Sub

    Private Function MyIsDate(ByVal s As String) As Date
        If IsDate(s) Then
            Return Date.Parse(s)
        Else
            Return Nothing
        End If
    End Function

    Private Function DateTryParse(ByVal s As String) As Date
        Dim dt As Date
        Try
            dt = Date.Parse(s)
        Catch ex As Exception
            dt = Nothing
        End Try
        Return dt
    End Function


P.S.  In the case of validating a few dates for a GUI form, even DateTryParse would have acceptable time performance.  But IsDate's cleaner anyway.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.