Bobski Bobski - 1 month ago 11
Vb.net Question

VB.Net Validating Date

Came across a small issue - I have a function where I pass DATE as String. This Date then gets passed as parameter to a stored procedure where I validate it, and it returns a value (0,1) whether it's valid or not. Here's what's going on code wise...

If CheckDateSP(mskAppointment.Text) Then
'Great now lets use this date
else
msgbox "Invalid date, re-enter please"
End if


Passing it into a function.....

Public Function CheckDateSP(ByVal CheckThisDate As String) As Boolean
'Setting Connection strings and all the good stuff
'here's where it gives me an error
Dim vDate As DateTime = CheckThisDate <----HERE is the error

End Function


Now here's the interesting part - I only get an error if I input a date like...


13/13/2016


Everything works perfectly fine if I enter dates such as these...


12/12/2017 , 10/10/2014


or any other date as long as month is less than 13

The error I get is....


ERROR converting from String '13/13/2016' to Type Date is not Valid.

Answer

Try this

Dim input As String = "13/13/2016"

Dim dt As DateTime
If DateTime.TryParseExact(input, "MM/dd/yyyy", New Globalization.CultureInfo("en-US"), Globalization.DateTimeStyles.None, dt) Then
    MessageBox.Show(String.Format("The string '{0}' parsed to '{1:yyyy-MM-dd hh:mm:ss}'", input, dt))
Else
    MessageBox.Show(String.Format("Couldn't parse '{0}'", input))
End If

The call to TryParseExact returns true when it's in the correct format, and false when it's not. Note, the format provided to TryParseExact is in the form month/day/year and I used Globalization.CultureInfo("en-US") because I'm in the US.

Comments