Reputation: 8188
What is the best way to validate a date, that it is actually a date if the input format is in CCYYMMDD as a string (i.e. "20101210")?
Upvotes: 1
Views: 545
Reputation: 34846
If you want an exception thrown if the date is not valid, then do this:
Dim date As Datetime = DateTime.ParseExact(theDateString, "yyyyMMdd", _
CultureInfo.InvariantCulture)
If you do not want an exception thrown if the data is not valid, then do this:
Dim myDate As Date
If Date.TryParseExact(theDateString, "yyyyMMdd", CultureInfo.CurrentCulture, _
DateTimeStyles.None, myDate) Then
' Conversion succeeded
Else
' Conversion failed
End If
Upvotes: 6
Reputation: 31394
Use DateTime.TryParseExact. It takes a date format string along with a date string and will return false if the string does not match the format exactly.
Upvotes: 0