DateTime解析TextBox的文本引发异常

DateTime parsing of TextBox's text raising exception

我正在使用这个脚本作为日期选择器:

<script type="text/javascript">
    $(function () {
        $("[id$=txtDate]").datepicker({
            dateFormat: 'dd/m/yy',
            showOn: 'button',
            buttonImageOnly: true,
            buttonImage: 'http://192.168.211.71/Imagens/calendar_icon.png'
        });
    });
</script>

$("[id$=txtDate]").datepicker({ 在这一行中,我将日期选择器分配给 txtDate 控件 (TextBox)。当我试图将它作为参数添加到存储过程时出现问题:

Cmd.Parameters.Add("@DataPedido", Data.SqlDbType.DateTime).Value = DateTime.ParseExact(TxtDate.Text, "dd/M/yyyy", Nothing)

我明白了 String was not recognized as a valid DateTime. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

如何正确地将文本框的值解析为 DateTime?

如果将 Nothing 作为第三个参数传递给 DateTime.ParseExact,则表示:"use my current culture's date-separator instead of /"。但实际上你想使用斜杠作为分隔符。因此你可以使用 InvariantCulture:

Dim dt = DateTime.ParseExact(TxtDate.Text, "dd/M/yyyy", System.Globalization.CultureInfo.InvariantCulture) 

另一种屏蔽这种特殊格式说明符的方法是在周围使用撇号:

DateTime.ParseExact(TxtDate.Text, "dd'/'M'/'yyyy", Nothing) 

这里是相关的documentation:

The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture.

并在 DateTime.ParseExact 中提到:

If provider is null, the CultureInfo object that corresponds to the current culture is used.


我想这是 jQuery-Datepicker 控件的问题。看看这里:

ASP.NET textbox with jQuery UI DatePicker value lost when doing a postback