【问题标题】:DateTime parsing of TextBox's text raising exceptionTextBox的文本引发异常的DateTime解析
【发布时间】:2015-02-12 19:54:14
【问题描述】:

我将此脚本用作日期选择器:

<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 控件(文本框)。当我尝试将其作为参数添加到存储过程时出现问题:

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?

【问题讨论】:

    标签: asp.net vb.net datetime


    【解决方案1】:

    如果您将Nothing 作为第三个参数传递给DateTime.ParseExact,您会说:“使用我当前文化的日期分隔符而不是 /”。但实际上你想使用斜杠作为分隔符。因此你可以使用InvariantCulture:

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

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

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

    这里是相关的documentation

    “/”自定义格式说明符表示日期分隔符,它 用于区分年、月和日。 适当的 本地化日期分隔符是从 当前或指定的 DateTimeFormatInfo.DateSeparator 属性 文化

    DateTime.ParseExact 中提到:

    如果 provider 为 null,则对应的 CultureInfo 对象 使用当前文化


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

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

    【讨论】:

    • Cmd.Parameters.Add("@DataPedido", Data.SqlDbType.DateTime).Value = DateTime.ParseExact(TxtDate.Text, "dd/M/yyyy",System.Globalization.CultureInfo.InvariantCulture) 仍然得到同样的错误。
    • 这是用户从日历(日期选择器)脚本中选择的任何内容。示例:“2015 年 2 月 2 日”
    • @MartimCosta:您可以看到它适用于上述两种方法:Dim dt = DateTime.ParseExact("02/2/2015", "dd/M/yyyy", System.Globalization.CultureInfo.InvariantCulture) dt = DateTime.ParseExact("02/2/2015", "dd'/'M'/'yyyy", Nothing)。有没有用调试器查看过值是否真的是"02/2/2015"
    • 我刚刚运行了调试器,你是对的,TxtDate.text = "" 尽管我可以在页面上看到日期。
    • 文本框没有绑定任何东西。我应该在哪里添加支票?我尝试将它添加到 txtDate_LoadPage_Load 但它不起作用。
    猜你喜欢
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 2021-11-03
    • 1970-01-01
    相关资源
    最近更新 更多