Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Valid Date

Posted on 2004-11-04
5
Medium Priority
?
227 Views
Last Modified: 2010-04-23
how do you verify what's in a text box is a valid date?
0
Comment
Question by:dblanch12
  • 2
3 Comments
 
LVL 12

Expert Comment

by:farsight
ID: 12499675
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
 
LVL 4

Expert Comment

by:Glom
ID: 12502202
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
 
LVL 12

Accepted Solution

by:
farsight earned 200 total points
ID: 12504367
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

Featured Post

[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?

581 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question