3

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

1
  • 1
    I think you should learn about DateTime.TryParse and DateTime.TryParseExact. Commented Apr 6, 2017 at 20:12

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

So anything that doesn't parse as a DateTime is null? That doesn't exactly help with his current problem, which is a date formatting issue. In addition, this would hide any date format error.
Fair enough... I added another condition to alert the user on bad input. The value does need to be converted to a date at some point.
-1

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"
});

4 Comments

How do you know jQuery date picker is being used?
He said so in his post.
He said "date picker". I imagine there's hundreds of date pickers out there.
ok, its a Jquery issue, this format works, 'M/dd/yyyy' other ones gimme the same error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.