Conversion of varchar into datetime data type

This is in Microsoft SQL Server Management Studio; I have a column Order_Date in my table, and the data type is datetime.

In my ASP.NET web application, I am inserting the date using this query:

"INSERT INTO Order (ORDER_DATE) VALUES ('" + System.DateTime.Now + "')";

I’ve done the same thing before in another project but didn’t get error there. Here I’m getting error when try to insert data. How can I solve this error?

Conversion of varchar into datetime data type

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

System.DateTime.Now will automatically be converted to a string by C# when it is appended to your INSERT string. However the string it produces will be dependent on the regional/culture settings on the box on which it is executing. It is exceptionally unlikely to produce a datetime string format that SQL understands. So you need to ensure that the correct format is used by explicitly setting it when the string is generated:

"INSERT INTO Order (ORDER_DATE) Values ('" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')";

Method 2

You could just make it a SqlType like:

"INSERT INTO Order (ORDER_DATE) Values ('" + new System.Data.SqlTypes.SqlDateTime(DateTime.Now).ToString() + "');"

Check out:
https://docs.microsoft.com/en-us/dotnet/api/system.data.sqltypes.sqldatetime


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x