DateTime format to SQL format using C#

前端 未结 15 1269
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 02:47

I am trying to save the current date time format from C# and convert it to an SQL Server date format like so yyyy-MM-dd HH:mm:ss so I can use it for my UP

15条回答
  •  一个人的身影
    2020-11-28 03:14

    The correct answer was already given "use parameters". Formatting a date and passing it as a string to SQL-Server can lead to errors as it depends on the settings how the date is interpreted on the server side. In europe, we write '1.12.2012' to indicate december 1st 2012, whereas in other countries this might be treated as january 12th.

    When issuing statements directly in SSMS I use the format yyyymmdd which seem to be quite general. I did not encounter any problems on the various installations I worked on so far.

    There is another seldom used format, which is a bit weird but works for all versions:

    select { d '2013-10-01' }
    

    will return the first of october 2013.

    select { ts '2013-10-01 13:45:01' }
    

    will return october 1st, 1:45:01 PM

    I strongly advice to use parameters and never format your own SQL code by pasting together homegrown formatted statement fragments. It is an entry for SQL injection and strange errors (formatting a float value is another potential issue)

提交回复
热议问题