我下面的代码将文件名的某些部分分配给一个变量。这里重要的是变量“yearandmonth”,它是一个格式为“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"
如何确保“yearandmonth”的输出是有效的年、月并且包含“-”?
最佳答案
您可以使用 DateTime.TryParse 方法来验证日期字符串是否是有效的日期格式,如下代码所示:
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
关于.net - 如何确保日期有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45025289/