ProblemYou 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. SolutionSample 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. DiscussionThe 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 timesIt'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.
|