使用vb.net在SQL中保存日期

时间:2022-05-09 20:52:21

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:

但是当你去约会的时候,比如“10/01/2016”,我就会犯这样的错误:

Conversion from string "10/30/2016" to type 'Date' is not valid

将字符串“10/30/2016”转换为类型“Date”无效

could you please help

你能请帮助

2 个解决方案

#1


2  

Use TryParse to convert the text value to a date.

使用TryParse将文本值转换为日期。

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

#2


-1  

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

如果您使用的是jQuery日期选择器,并且您的日期格式不是mm-dd-yy,您应该将datepicker配置为该格式:

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

#1


2  

Use TryParse to convert the text value to a date.

使用TryParse将文本值转换为日期。

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

#2


-1  

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

如果您使用的是jQuery日期选择器,并且您的日期格式不是mm-dd-yy,您应该将datepicker配置为该格式:

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