字符串在C asp.net中未被识别为有效的日期时间

字符串在C asp.net中未被识别为有效的日期时间,asp.net,c#-4.0,c#-3.0,c#-2.0,Asp.net,C# 4.0,C# 3.0,C# 2.0,我想从excel单元格导入日期值。具有2013年10月10日格式的单元格值。我想将其转换为datetime数据类型。我的代码获取错误字符串未被识别为有效的datetime //代码 OleDbCommand olecmd = new OleDbCommand("select * from [Sheet1$]", olecon); OleDbDataReader olerdr = olecmd.ExecuteReader();

我想从excel单元格导入日期值。具有2013年10月10日格式的单元格值。我想将其转换为datetime数据类型。我的代码获取错误字符串未被识别为有效的datetime

//代码

      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();
    }
    }
有人帮我解决这个问题吗

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

您在ParseExact中提供的格式错误,与您传递的日期字符串不匹配。你需要不同的格式。对于需要dd的日子,对于需要MMMM的月份,对于需要yyyy的年份,必须使用空格作为分隔符

在MSDN上使用字符串格式进行日期转换值得一读

DateTime dt = DateTime.ParseExact(deldate, "dd MMMM yyyy", CultureInfo.InvariantCulture);
具有2013年10月10日格式的单元格值

您在ParseExact中提供的格式错误,与您传递的日期字符串不匹配。你需要不同的格式。对于需要dd的日子,对于需要MMMM的月份,对于需要yyyy的年份,必须使用空格作为分隔符

在MSDN上使用字符串格式进行日期转换值得一读

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

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

下面是我自己的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;
    }

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

下面是我自己的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;
    }
从右下角选择日期时间设置,并从这里更改格式

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


我想在MM dd yyyy中将其插入sql数据库。。我还尝试了上面给出的代码。仍然有相同的错误。在哪一行出现错误,请检查数据库过程参数/列格式(如果它来自数据库)。我想在MM dd yyyy中将其插入sql数据库。。我还尝试了上面给出的代码。仍然有相同的错误。在哪一行出现错误,请检查数据库过程参数/列格式(如果它来自数据库)