Recipe 7.11. Parsing and Validating Dates and Times


Problem

You want to parse a string to convert it to a date or time, and you want to avoid using error trapping to detect incorrectly formatted strings.

Solution

Sample code folder: Chapter 07\ParseDate

Use the IsDate() function to predetermine the validity of a string's representation of a date or time, and then use the Date.Parse() method on the string to reliably convert it to a Date.

Discussion

The new TRy…Catch…End Try structured error trapping is a great tool for catching unexpected exceptions in applications, but it's always best to make sure you have clean data before you use it in a way that could generate an error. For example, it's best to use the IsDate() function to check a date's validity before trying to use it in your main code's logic; this will turn up errors such as misspelled month names.

The following code uses IsDate() to validate a string and allow conversion to a date value only if the string passes the test:

 Dim testDate As String Dim results As New System.Text.StringBuilder ' ----- Test an invalid date. testDate = "Febtember 43, 2007" If (IsDate(testDate) = True) Then _    results.AppendLine(Date.Parse(testDate).ToString) ' ----- Test a time. testDate = "23:57:58" If (IsDate(testDate) = True) Then _    results.AppendLine(Date.Parse(testDate).ToString) ' ----- Test a date. testDate = "December 7, 2007" If (IsDate(testDate) = True) Then _    results.AppendLine(Date.Parse(testDate).ToString) ' ----- Test a standardized   date and time. testDate = "2007-07-04T23:59:59" If (IsDate(testDate) = True) Then _    results.AppendLine(Date.Parse(testDate).ToString) ' ----- Test another standardized UTC date and time. testDate = "2007-07-04T23:59:59Z" If (  IsDate(testDate) = True) Then _    results.AppendLine(Date.  Parse(testDate).ToString) ' ----- Display the results. MsgBox(results.ToString()) 

As shown in Figure 7-11, the first string is a bad one, so it's not converted. The remaining four strings are correctly parsed to Dates.

Figure 7-11. Dates parsed from a variety of string representations of dates and times


It's safe to assume that any string that returns true when passed to IsDate() will not cause an exception when passed to a Date's Parse() method.

The Visual Basic CDate() conversion function also changes a string date to its true Date counterpart:

 Dim realDate As Date = CDate("January 1, 2007") 





Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net