5

我有这个例子,它给了我异常“从字符串 x 到 dateTime 的转换无效”

这是我验证日期时间的方法。

示例日期字符串:“27/03/1985”

Public Function validateDateColumn(ByRef FieldName As String) As Boolean

    Try
        If IsDate(FieldName) Then
            Dim actualDate As DateTime = CDate(FieldName)
            Dim DtLicExp As DateTime = CDate(actualDate.ToString("d", Thread.CurrentThread.CurrentCulture))
            FieldName = DtLicExp.ToString("MM/dd/yyyy")
            Return True
        End If
    Catch ex As Exception
        'FieldName &= "Format must be MM/dd/yyyy"
        Return False
    End Try

End Function

将这个日期字符串格式验证为日期时间的任何想法。

我想将此日期“27/03/1985”转换为日期时间。

我正在使用带有 vb.net 的 asp.net。

4

3 回答 3

7

看看使用DateTime.TryParseExact 方法DateTime.ParseExact 方法

于 2010-12-01T18:52:44.290 回答
1

此实现将解析格式dd/MM/yyyy的日期并将日期字符串更新MM/dd/yyyy为您需要的日期。DateTime.TryParseExact允许您指定需要解析的日期格式。

Public Function validateDateColumn(ByRef FieldName As String) As Boolean

  validateDateColumn = False

  Dim dateValue As DateTime

  if DateTime.TryParseExact(FieldName, _
      "dd/MM/yyyy", CultureInfo.InvariantCulture, _
      DateTimeStyles.None, dateValue) Then

      validateDateColumn = True
      FieldName = dateValue.ToString("MM/dd/yyyy")
  End If

End Function
于 2010-12-01T18:55:09.880 回答
0

你可以试试这个TryParse方法。

Dim myDateString as String = "7/7/2010"
Dim myDate as DateTime
Dim isDate As Boolean = DateTime.TryParse(myDateString, myDate)

If isDate Then
    ' Yay I'm a real date
End If
于 2010-12-01T18:53:50.873 回答