0

I get this error "Conversion failed when converting date and/or time from character string." My code is below.

string[] closedate = lbldate_end.Text.Split(' ');
string txtdate = closedate[0];
string txttime = closedate[1];

Am getting date from SQL database in a label. But i get it as 15-05-2014 00:00:00 so am splitting it. and then updating in database.but error is thrown.

Conversion failed when converting date and/or time from character string

Please someone help me

Mo Patel
  • 2,321
  • 4
  • 22
  • 37

2 Answers2

1

Use the SqlReader.GetDateTime function in order to retrieve a date time column.

You can then use the DateTime.ToString function with custom formatting to fetch the date and the time in the desired format:

// assuming the column CLOSE_DATE is at position 5 = the fifth column from the table
var timestamp = myReader.GetDateTime(5);
Console.WriteLine(timestamp.ToString("yyyy-MM-dd")); // date only
Console.WriteLine(timestamp.ToString("HH:mm:ss")); // time only

or

var timestamp = (DateTime)myReader["CLOSE_DATE"];
Console.WriteLine(timestamp.ToString("yyyy-MM-dd"));
Console.WriteLine(timestamp.ToString("HH:mm:ss"));

Assuming the field contains today and some time, then the output would be something like:

2014-05-15
13:18:31

Another possible solution could be found in this SO post.

Community
  • 1
  • 1
keenthinker
  • 7,645
  • 2
  • 35
  • 45
  • it throws me error **Error The best overloaded method match for 'string.ToString(System.IFormatProvider)' has some invalid arguments** – user3331850 May 15 '14 at 11:28
  • If you are still using the `myReader["CLOSE_DATE"].ToString();` then remove the `.ToString()` in order to fetch the result as DateTime object and not as string and try again. Applying date formats on string is not possible. – keenthinker May 15 '14 at 11:29
  • Glad that the answer helped. – keenthinker May 15 '14 at 11:41
0

You might want to use

end.Text = (myReader["CLOSE_DATE"] as DateTime).ToString();

instead of your

end.Text = myReader["CLOSE_DATE"].ToString();
msmolcic
  • 6,407
  • 8
  • 32
  • 56