我正在使用vb.net,框架3.5和winform应用程序。我正在从数据库加载记录,其中包含日期为文本字符串:
4/5/2016 (d/M/yyyy) ' 4th May 2016
06/05/2016 (dd/MM/yyyy) ' 6th May 2016
05/8/2016 (dd/M/yyyy) ' 5th August 2016
6/08/2016 (d/MM/yyyy) ' 6th August 2016
解析日期,我正在使用:
Public Function GetDate(ByVal DateTxt As String) As Date
Dim date_ As Nullable(Of Date) = Nothing
Try
date_ = DateTime.ParseExact(DateTxt, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
Catch ex As Exception
End Try
If date_ Is Nothing Then
Try
date_ = DateTime.ParseExact(DateTxt, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture)
Catch ex As Exception
End Try
End If
If date_ Is Nothing Then
Try
date_ = DateTime.ParseExact(DateTxt, "dd/M/yyyy", System.Globalization.CultureInfo.InvariantCulture)
Catch ex As Exception
End Try
End If
If date_ Is Nothing Then
Try
date_ = DateTime.ParseExact(DateTxt, "d/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
Catch ex As Exception
End Try
End If
Return date_
End Function
有没有更好的方法来解析这些相似类型的格式并获得Exact日期?
答案 0 :(得分:2)
如果您不想将日期限制为特定格式,请使用RBT的答案。但是,如果要将日期限制为指定的格式,则应使用TryParseExact
结构的DateTime
方法:
Public Function GetDate(ByVal DateTxt As String) As Nullable(Of Date)
Dim date_ As Date
Dim AcceptableFormats As String() = {"dd/MM/yyyy", "d/M/yyyy", "dd/M/yyyy", "d/MM/yyyy"}
If Not DateTime.TryParseExact(DateTxt, AcceptableFormats, System.Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, date_) Then
Return Nothing
End If
Return date_
End Function
请注意,此函数返回类型为nullable(of date)
而不是date
。
答案 1 :(得分:1)
使用ParseExact
API,无需在尝试将其与各种可能模式匹配的情况下放置太多if-else块。我宁愿建议您直接使用TryParse
API,它将为您提供帮助。看看下面的代码片段。这样你也可以避免这么多try-catch块:
Public Function GetDate(ByVal DateTxt As String) As Date
Dim date_ As Nullable(Of System.DateTime) = Nothing
DateTime.TryParse(DateTxt, date_)
Return date_
End Function