Amr Elnashar
Amr Elnashar

Reputation: 1769

Converting Date string to DateTime Format vb.net

I have this example and it gives me exception "Conversion from string x to dateTime is invalid"

here is my method to validate Datetime.

Example Date string : "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

any idea to validate this date string formate to datetime.

I want to convert this date "27/03/1985" to datetime.

I'm using asp.net with vb.net.

Upvotes: 5

Views: 53928

Answers (3)

spolto
spolto

Reputation: 4551

This implementation will parse dates of the format dd/MM/yyyy and update the date string to the MM/dd/yyyy as you require. DateTime.TryParseExact allows you to specify the format of the date that you need to parse.

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

Upvotes: 1

Joel Etherton
Joel Etherton

Reputation: 37543

You could try the TryParse method.

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

Upvotes: 0

Adriaan Stander
Adriaan Stander

Reputation: 166506

Have a look at using DateTime.TryParseExact Method or DateTime.ParseExact Method

Upvotes: 7

Related Questions