【问题标题】:Unable to cast String to DateTime无法将字符串转换为 DateTime
【发布时间】:2013-08-31 08:24:39
【问题描述】:

我使用 ajax 日历扩展器关注 TextBox,并且在 TextChanged 事件中我正在调用 "txtFromDate_TextChanged" 函数。

asp 代码:

<asp:TextBox ID="txtFromDate" runat="server" AutoPostBack="True" 
                            ontextchanged="txtFromDate_TextChanged"></asp:TextBox>
  asp:CalendarExtender ID="txtFromDate_CalendarExtender" Format="dd/MM/yyyy" runat="server" Enabled="True"
                            TargetControlID="txtFromDate">
                        </asp:CalendarExtender>

c#代码:

protected void txtFromDate_TextChanged(object sender, EventArgs e)
{
  if (txtFromDate.Text != "")
  {
    DateTime fromdate = Convert.ToDateTime(txtFromDate.Text);
    Query = Query + "And   CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, ord_del_date))) >= '" + fromdate.ToString("yyyy'-'MM'-'dd") + "'";

  }
}

当我通过 Visual Studio 进行调试时,甚至当我将站点托管在本地 IIS 服务器上时,此代码都可以正常工作。 问题是,当我在 在线托管服务器 上托管网站时,当我从日历中选择日期并调用 textchanged 事件时,会出现以下错误:

错误:

String was not recognized as a valid DateTime.

我知道由于以下行而出错:

DateTime fromdate = Convert.ToDateTime(txtFromDate.Text);

但我在这段代码中没有发现任何错误。 此代码在 Visual Studio 或托管在 IIS 上时运行良好,但我完全困惑为什么它在托管服务器上托管时不起作用。我完全糊涂了。请帮帮我。

【问题讨论】:

  • 那么txtFromDate.Text 的值是多少?为什么要动态构建 SQL 而不是使用参数化 SQL?我的猜测是问题出在使用系统本地文化的服务器上,您应该使用DateTime.ParseExact 指定不变的文化。

标签: asp.net c#-4.0 datetime ajaxcontroltoolkit textchanged


【解决方案1】:

尝试将 aspx 中的日期格式更改为

dd-MMM-yyyy (if you want month)

dd-MM-yyyy (if you want only month)

【讨论】:

    【解决方案2】:

    试试这个:

    IFormatProvider provider = new System.Globalization.CultureInfo("gu-IN", true);
    DateTime dtime = DateTime.Parse(txtFromDate.Text, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
    

    【讨论】:

      【解决方案3】:
      fromdate.ToString("yyyy'-'MM'-'dd")
      

      改变它的工作格式

      fromdate.ToString("yyyy-MM-dd")
      

      【讨论】:

        【解决方案4】:
        DateTime fromdate = DateTime.ParseExact(txtToDate.Text, "dd/MM/yyyy", null);
        
        Query = Query + "And   CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, ord_del_date))) >= '" + fromdate.ToString("yyyy'-'MM'-'dd") + "'";
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-10
          • 1970-01-01
          • 2021-03-13
          • 2016-09-27
          • 1970-01-01
          相关资源
          最近更新 更多