Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

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

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

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top