Skip to content
Advertisement

Mismatches on DateTime between C# and SQL server

I create DateTime in C# like this

DateTime oDate = Convert.ToDateTime(xate);

that returns 22/09/2020 01:27:00 ب.ظ}

and save it in SQL server after saving I see the time that stored is Weird like this

enter image description here

and when I try to run a SQL command like this

I get this error

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

I figure out the time that generates in C# is vice versa the format in the SQL Server.

I don’t know how to save DateTime in C# to SQL Server.

My code for saving datatime in SQL Server is:

Advertisement

Answer

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

The problem is that you insert a string ' ' into your SQL Database instead of a DateTime Object like you specified.

We can create a DateTime Object from a string easily if we use DateTime.TryParseExact()

Example:

Now we can also insert that Variable into our SQL Statement as it’s value.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement