【问题标题】:String was not recognized as a valid DateTime in C# asp.net在 C# asp.net 中,字符串未被识别为有效的 DateTime
【发布时间】:2014-02-21 12:07:13
【问题描述】:

我想从 Excel 单元格中导入日期值。具有“2013 年 10 月 10 日”格式的单元格值。我想将其转换为日期时间数据类型。我的代码出现错误“字符串未被识别为有效日期时间”

//代码

      OleDbCommand olecmd = new OleDbCommand("select * from [Sheet1$]", olecon);


               OleDbDataReader olerdr = olecmd.ExecuteReader();
                 while (olerdr.Read())
                 {
                    deldate = olerdr.GetValue(13).ToString();
                     using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["irisdb"].ConnectionString))
                     {
                         con.Open();
                         SqlCommand cmd = new SqlCommand("procdamandrugs", con);
                         cmd.CommandType = CommandType.StoredProcedure;
     DateTime dt = DateTime.ParseExact(deldate, "MM/dd/yyyy", CultureInfo.InvariantCulture);//getting error in this line
                         SqlParameter par9 = new SqlParameter();
                         par9.ParameterName = "@deleffdate";
                         par9.SqlDbType = SqlDbType.DateTime;
                         par9.Value = dt;
                         cmd.Parameters.Add(par9);
 cmd.ExecuteNonQuery();
    }
    }

谁能帮我解决这个问题。

【问题讨论】:

    标签: asp.net c#-4.0 c#-3.0 c#-2.0


    【解决方案1】:

    具有“2013 年 10 月 10 日”格式的单元格值。

    您在 ParseExact 中给出的格式错误,与您传递的日期字符串不匹配。您需要的格式与您提供的格式不同。一天你需要dd,一个月你需要MMMM,一年你需要yyyy,你必须给空格作为分隔符。

    MSDN 上的文章Custom Date and Time Format Strings 使用字符串格式进行日期转换非常值得。

    DateTime dt = DateTime.ParseExact(deldate, "dd MMMM yyyy", CultureInfo.InvariantCulture);
    

    【讨论】:

    • 我想将它插入到“MM-dd-yyyy”中的sql数据库中。我也尝试了上面给出的代码。仍然有同样的错误。
    • 在哪一行出错,检查数据库过程参数/列格式是否来自数据库
    【解决方案2】:

    我建议在构造 SQL 对象之前使用 DateTime.TryParse 方法。在与您的数据库进行对话之前,请确保您有高质量的输入。

    http://msdn.microsoft.com/en-us/library/ch92fbc1%28v=vs.110%29.aspx

    以下是我自己的 asp.net 应用程序代码示例

        // Validation
        DateTime dtOut_StartDate;
        if (!DateTime.TryParse(txtStartDate.Text, out dtOut_StartDate))
        {
            Message = "Start date is not a valid format.";
            txtStartDate.CssClass = ErrorCssClass.TextBox;
            txtStartDate.Focus();
            return false;
        }
    

    【讨论】:

      【解决方案3】:

      从右下角选择日期时间设置并从这里更改格式......

      【讨论】:

        猜你喜欢
        • 2016-09-17
        • 1970-01-01
        • 2011-09-12
        • 2021-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-22
        相关资源
        最近更新 更多