date saving in SQL using vb.net

I m using the following code to save the date from a textbox and selecting the date using date picker.

 If (String.IsNullOrEmpty(DobTxt.Text)) Then
        SQLCmd.Parameters.Add("@DOB", SqlDbType.Date).Value = DBNull.Value
    Else
        Dim DOBDte As date= String.Format("{0:YYYY-MM-dd}", DobTxt.Text.Trim())
        SQLCmd.Parameters.Add("@DOB", SqlDbType.Date).Value = DOBDte
    End If

Now the code works just fine with dates like “”

but when you go for a date like “10/01/2016” I get this error:

Conversion from string “10/30/2016” to type ‘Date’ is not valid

could you please help

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use TryParse to convert the text value to a date.

Dim dateValue As Date
If String.IsNullOrWhiteSpace(DobTxt.Text) Then
    SQLCmd.Parameters.Add("@DOB", SqlDbType.Date).Value = DBNull.Value
ElseIf Date.TryParse(DobTxt.Text.Trim(), dateValue) Then
    SQLCmd.Parameters.Add("@DOB", SqlDbType.Date).Value = dateValue
Else
    ' alert the user that there is invalid input
End If

Method 2

If you’re using jQuery date picker, and your date format is not mm-dd-yy you should configure datepicker to that format:

$( ".selector" ).datepicker({
  dateFormat: "yy-mm-dd"
});


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x