Unable to convert DateTime from SQL Server to C # DateTime

I wrote a C # program that uses dates. It takes a value from a SQL Server table. I used Windows 7 and the program worked fine. I had this line of code:

DateTime fechaOperacion = Convert.ToDateTime(reader["FechaOperacion"]);

The reader returned the date in 24-hour format, and I was able to convert it to a variable DateTime.

Now I upgraded the system to Windows 10, and the same line of code produces the following error:

The string was not recognized as a valid DateTime. there is an unknown word starting at index 20.

And now the reader is back. format, and at index 20 - mm or pm

I have tried the following things:

  • Rephrase the line of code to:

    • Convert.ToDateTime(reader["FechaOperacion"], System.Globalization.CultureInfo.InvariantCulture)
    • reader.GetDateTime(reader.GetOrdinal("FechaOperacion"));
  • Convert culture to 24h format

    System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(1033);
    

But none of this works, I do not know what else to do.

+4
2

, / ( [n][var]char({max|n}) : [n]text). :

  • /
  • /
  • /
  • .
  • .

, , datetime/date/time/etc. ( ), - .


. , , select . ; , .

+7

,

string[] mfs = { "MM/dd/yyyy HH:mm:ss",  "MM/dd/yyyy h:mm:ss tt"};

var dat = DateTime.ParseExact("04/23/1945 8:45:22 PM", mfs, 
                System.Globalization.CultureInfo.InvariantCulture, 
                System.Globalization.DateTimeStyles.None);
0

Source: https://habr.com/ru/post/1656235/


All Articles