代码之家  ›  专栏  ›  技术社区  ›  DreamTeK

在.NET中返回带有TryParseExact的默认日期

  •  0
  • DreamTeK  · 技术社区  · 8 年前

    为什么此函数不返回默认值?

    1900-01-01 应退回。

    而是返回 01/01/0001

    Public Shared Function ParseDate(FieldName As Object) As Date
      Dim ID As Date = "1900-01-01"
    
      If TypeOf FieldName Is TextBox Then
        If Date.TryParseExact(FieldName.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, ID) Then
          ID = FieldName.Text
        End If
      End If
    
      Return ID
    End Function
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   Tim Schmelter    8 年前

    你误解了 DateTime.TryParse 作品它不会退还你的通行证 DateTime 作为回退值。out参数对输入参数不感兴趣。 TryParse 将为 日期时间 MinValue 如果无法解析,则返回out参数。那是 documented

    当此方法返回时,包含 日期时间 s中包含的日期和时间,如果转换成功, MinValue 如果转换失败 。如果s 参数为 null 未初始化通过。

    DateTime.MinValue 如果无法成功解析。


    但是你应该使用返回的 Boolean 无论如何,要确定是否可以对其进行解析:

    Dim validDate = Date.TryParseExact(FieldName.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, ID)
    

    上述函数可以重写为:

    Public Shared Function ParseDate(FieldName As Object) As Date
        If TypeOf FieldName Is TextBox Then
            Dim dt as Date
            If Date.TryParseExact(FieldName.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, dt) Then
                Return dt
            End If
        End If
    
        Return New Date(1900, 1, 1)
    End Function