.net - 如何确保日期有效?

标签 .net vb.net date datetime

我下面的代码将文件名的某些部分分配给一个变量。这里重要的是变量“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/

相关文章:

vb.net - 当我将文本文件复制到服务器上的另一个文件夹时,对路径 ' ' 的访问被拒绝

python - 我想生成连续的日期

r - 计算 ID 为 "break variable"的特定日期的天数

.net - fortify 软件与 Visual Studio 2012 兼容吗?

c# - WPF MessageBox 不等待结果 [WPF NotifyIcon]

vb.net - 向 VB.net 添加关键字? ("Exists"与 "IsNot Nothing")

Java不断检查日期

.net - 通过 Rally rest .net api 提交缺陷时如何设置自定义 WebLink 字段值?

c# - 如何捕获 .NET 应用程序中的所有异常/崩溃

vb.net - 使用 VB.NET 进行 OAuth 身份验证