I wrote a program in C# that uses dates. It takes the value from a SQL Server table. I was using Windows 7 and the program worked fine. I had this line of code:
DateTime fechaOperacion = Convert.ToDateTime(reader["FechaOperacion"]); The reader returned a date in a 24h format and I was able to convert that to a DateTime variable.
Now I did a system upgrade to Windows 10 and that same line of code is throwing the following error:
String was not recognized as a valid DateTime. there is an unknown word starting at index 20.
And now the reader returns a.m. / p.m. format, and at index 20 there is a.m or p.m.
I have tried the following things:
Rephrasing the line of code to:
Convert.ToDateTime(reader["FechaOperacion"], System.Globalization.CultureInfo.InvariantCulture)reader.GetDateTime(reader.GetOrdinal("FechaOperacion"));
Convert the culture to 24h format
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(1033);
But none of that seems to work, I don't know what else to do.
reader.GetDateTime(reader.GetOrdinal("FechaOperacion")), which is the correct way to read aDATETIMEcolumn independently of any format?reader["FechaOperacion"]returning? the fact that it mentionsStringmeans that it isn't "sql DateTime" - a SQLdatetimevalue would be fine and doesn't need to be parsed. So: what is it?FechaOperacionis a DATETIME column, then it sounds like it's a display issue. What happens if you do avar dateStr = fechaOperacion.ToString("dd/MM/yyyy HH:mm:ss");? What is the value ofdateStr?datetimeto a C# DateTime. They are equivalent. If you think you need to convert anything, it's because you are using strings instead ofdatetime. Instead of usingConvertyou shuould be able to use a direct cast, ie(DateTime). If you can't you are returning strings