String was not recognized as a valid DateTime in C# asp.net

随声附和 提交于 2019-12-11 06:56:27

问题


I want to import date value from excel cell. cell value having "10 October 2013" format. I want to convert it to datetime data type. My code getting error "string was not recognized as a valid datetime"

//code

      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();
    }
    }

Do any one help me to solve this issue.


回答1:


I recommend the utilizing the DateTime.TryParse method before constructing your SQL objects. Ensure you have quality input before having a conversation with your database.

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

Below is a sample from my own code for an asp.net application

    // 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;
    }



回答2:


cell value having "10 October 2013" format.

You are giving wrong format in ParseExact that does not match with the date string you are passing. You need different format than you gave. For day you need dd, for month you need MMMM and for year you need yyyy and you have to give spaces as separator.

It is worth the article Custom Date and Time Format Strings on MSDN for using the string formats for date conversion.

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



回答3:


Select Date Time setting from Right lower bottom & Change the format from here......



来源:https://stackoverflow.com/questions/21934089/string-was-not-recognized-as-a-valid-datetime-in-c-sharp-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!