Truncate Datetime to Second (Remove Milliseconds) in T-SQL

后端 未结 8 1447
庸人自扰
庸人自扰 2020-12-01 08:59

What is the best way to shorten a datetime that includes milliseconds to only have the second?

For example 2012-01-25 17:24:05.784 to 2012-01-25

相关标签:
8条回答
  • 2020-12-01 09:45

    Expanding on accepted answer by @Mikael Eriksson:

    To truncate a datetime2(7) to 3 places (aka milliseconds):

       -- Strip of fractional part then add desired part back in
       select dateadd(nanosecond,
                      -datepart(nanosecond, TimeUtc) + datepart(millisecond, TimeUtc) * 1e6,
                      TimeUtc) as TimeUtc
    

    The current max precision of datetime2(p) is (7) (from docs.microsoft.com)

    0 讨论(0)
  • convert(datetime, convert(varchar, @datetime_var, 120), 120)
    
    0 讨论(0)
提交回复
热议问题