chetan
chetan

Reputation: 335

String is not recognised as valid datetime in C#

I have the following line of code:

i am reading ex_date from excel(column sent_date) which is in format MM/DD/YYYY. sent_date is of type date and in database it is saving in the format of YYYY/MM/DD. i tried adding Datetime.ParseExact. but it gives "string is not recoganized as valid datetime".

    string ex_date = dr[2].ToString();
    DateTime date = new DateTime();
    date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
    string SentDateString = date.ToString("yyyy/MM/dd");
    cmd.Parameters.AddWithValue("?sentdate", SentDateString);

Upvotes: 2

Views: 1173

Answers (1)

Preet
Preet

Reputation: 994

If you are getting error on ParseExact: that means your value from excel is wrong. Make sure all values are correct.

It is working:see here

EDIT:

string ex_date = dr[2].ToString();
ex_date = ex_date.Split(' ')[0];
DateTime date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
string SentDateString = date.ToString("yyyy/MM/dd");
cmd.Parameters.AddWithValue("?sentdate", SentDateString);    

Because you are passing string value in sql datetime column. you need to convert string to datetime:

 string SentDateString = date.ToString("yyyy/MM/dd");
 DateTime SentDate = Convert.ToDateTime(SentDateString).Date;
 cmd.Parameters.AddWithValue("?sentdate", sentDate);

Hope it will help!

Upvotes: 1

Related Questions