I have a string variable containing a date formatted as YYYYMMDD
For example - Dim x as string = "20070314"
If I try to perform a type conversion as follows I get an error:
Dim y as Date = CDATE(x)
How can I perform a type conversion for the date format YYYYMMDD?
Thanks.
Private Function ConvertDate(ByVal value As String) As Date
' Converts a date in YYYYMMDD format to MM/DD/YYYY format.
If Not value.Length = 8 Then
Throw New ArgumentException("Invalid length")
End If
If Not IsNumeric(value) Then
Throw New ArgumentException("Not a valid 8-digit number.")
End If
Dim theYear As String = value.SubString(0, 4)
Dim theMonth As String = value.SubString(4, 2)
Dim theDay As String = value.SubString(6, 2)
Dim result As String = theMonth & "/" & theDay & "/" & theYear
If Not IsDate(result) Then
Throw New ArgumentException("value cannot be converted to a
valid date.")
End If
Return CDate(result)
End Function
Basically, parse it into it's constituent parts, then splice it back
together into the format you want. I'm sure there's a regular
expression you could use to do it, but I'm all for clear code that
maintenance programmers can read. Plus, I get to add lots of error
checking that validates the argument.
Hope this helps.
Mike