【问题标题】:String not recognized as valid datetime字符串未被识别为有效日期时间
【发布时间】:2012-05-18 00:48:55
【问题描述】:

我的代码给出了上述错误。

我已尝试根据以下链接进行更改:

String was not recognized as a valid DateTime “ format dd/MM/yyyy”

但还是不行。

如果有人能指出我正确的方向,将不胜感激。

我的代码如下:

foreach (GridViewRow row in GridView1.Rows)

        {

       // int RowIndex = 0;
       // GridViewRow row = (GridViewRow)GridView1.Rows[RowIndex];

            Int32 intresortID = Convert.ToInt32(Request.QueryString["TypeID"]);
            Label dtm = row.FindControl("Label1") as Label;
            Label strRoomType = row.FindControl("Label2") as Label;
            Label strDescription = row.FindControl("Label3") as Label;
            TextBox Qty = row.FindControl("intQtyTextBox") as TextBox;
            TextBox Price = row.FindControl("curPriceTextBox") as TextBox;
            Label intWSCode = row.FindControl("intWSCodeLabel") as Label;

            string connStr = ConfigurationManager.ConnectionStrings["bestandConnectionString"].ConnectionString;
            using (SqlConnection Con = new SqlConnection(connStr))
            {
                Con.Open();
                SqlCommand cmd = new SqlCommand("Update tblAvail set intqty=@intQty, curprice=@curprice where intresortid=@intresortid and dtm=@dtm and strroomtype=@strroomtype", Con);

cmd.Parameters.AddWithValue("@dtm", DateTime.ParseExact(dtm.Text.Trim(), "dd / MM / yyyy",null)); 给出错误的行

                cmd.Parameters.AddWithValue("@strroomtype", strRoomType.Text.Trim());
                cmd.Parameters.AddWithValue("@intQty", Qty.Text.Trim());
                cmd.Parameters.AddWithValue("@curPrice", Price.Text.Trim());
                cmd.Parameters.AddWithValue("@intResortID", intresortID);

                cmd.ExecuteNonQuery();
                GridView1.EditIndex = -1;
                DataBind();

            }

在设计模式中:

  <ItemTemplate>
        <asp:Label ID="Label1" runat="server" 
                        Text='<%# Eval("Dtm", "{0:dd/MM/yyyy}") %>'></asp:Label>
  </ItemTemplate>

调试时dtm值为:

{Text = "18/05/2012"}

【问题讨论】:

  • 您能否调试该方法并查看日期值是如何输入的并将其发布在您的问题中?
  • 尝试使用 SqlDateTime.Parse 而不是 DateTime.ParseExact
  • 我收到错误提示 SQLDatetime 在当前上下文中不存在
  • Scorpion-Prince 修正问题,上面的值。
  • 你可以将第一个字符串转换为日期,然后尝试以特定格式检索吗?

标签: c# asp.net datetime formatexception datetime-parsing


【解决方案1】:

试试

DateTime.ParseExact(dtm.Text.Trim(), "dd/M/yyyy", System.Globalization.CultureInfo.InvariantCulture)

四个y而不是3和InvariantCulture

【讨论】:

  • 这是一个拼写错误,抱歉。已修改我的代码以显示正确的方法。它仍然给出错误。
  • @user1270384:我还编辑了我的答案并添加了CultureInfo.InvariantCulture
  • 不走运...仍然给出同样的错误。当我在调试模式下将鼠标悬停在 dtm.text ={"18/5/2012"}
  • @user1270384:它适用于18/05/2012。为什么月份中省略了零?尝试改用这种格式:dd/M/yyyy(编辑了我的答案)
  • 我已经在 LINQPad 中确认 Tim 的答案(DateTime.ParseExact with "dd/M/yyyy")适用于字符串 5 和 05 中的月份值
猜你喜欢
  • 1970-01-01
  • 2012-04-24
  • 1970-01-01
  • 1970-01-01
  • 2013-02-07
  • 2011-10-21
  • 2017-08-03
  • 1970-01-01
相关资源
最近更新 更多