How to ensure that the date is valid?
My code below assigns specific parts of a filename to a variable. The important thing here is the "yearandmonth" variable, which is a string formatted as "yyyy-mm"
Dim fileparts() As String
Dim delimiter As String = " - "
Dim company As String
Dim type As String
Dim bank As String
Dim bankaccount As String
Dim yearandmonth As String
Dim fileyear As String
Dim filemonth As String
fileparts = Split(localFileName, delimiter)
company = fileparts(0)
type = fileparts(1)
bank = fileparts(2)
bankaccount = fileparts(3)
yearandmonth = Left(fileparts(4), 7) ' RESULTS IN A STRING THAT WILL LOOK LIKE "yyyy-mm"
fileyear = Left(yearandmonth, 4) ' results in "yyyy"
filemonth = Right(yearandmonth, 2) ' results in "mm"
How can I ensure that the output with yearandmonth is a valid year, month, and contains "-"?
+3
source to share
1 answer
You can use DateTime.TryParse method to check if date string is a valid date format as below code:
Dim dateStrings() As String = {"yyyy-mm"}
Dim dateValue As Date
If DateTime.TryParseExact(mystring, dateStrings, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue) Then
'Do for Valid Date
Else
'Do for Invalid Date
End If
+2
source to share