简体   繁体   中英

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

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.

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

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

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM