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

后端 未结 8 1446
庸人自扰
庸人自扰 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:25

    The following has very fast performance, but it not only removes millisecond but also rounds to minute. See (http://msdn.microsoft.com/en-us/library/bb677243.aspx)

    select cast(yourdate as smalldatetime) from yourtable
    

    Edit:

    The following script is made to compare the scripts from Mikael and gbn I upvoted them both since both answers are great. The test will show that gbn' script is slightly faster than Mikaels:

    declare @a datetime
    declare @x int = 1 
    declare @mikaelend datetime
    
    declare @mikael datetime = getdate() 
    while @x < 5000000 
    begin   
      select @a = dateadd(millisecond, -datepart(millisecond, getdate()), getdate()) , @x +=1 
    end  
    set @mikaelend = getdate()
    
    set @x = 1 
    declare @gbnend datetime
    declare @gbn datetime = getdate() 
    while @x < 5000000
    begin 
      select @a = DATEADD(second, DATEDIFF(second, '20000101', getdate()), '20000101')  , @x +=1 
    end  
    set @gbnend = getdate()
    select datediff(ms, @mikael, @mikaelend) mikael, datediff(ms, @gbn, @gbnend) gbn 
    

    First run

    mikael      gbn
    ----------- -----------
    5320        4686
    

    Second run

    mikael      gbn
    ----------- -----------
    5286        4883
    

    Third run

    mikael      gbn
    ----------- -----------
    5346        4620
    
    0 讨论(0)
  • 2020-12-01 09:27
    --- DOES NOT Truncate milliseconds
    --- 2018-07-19 12:00:00.000
    SELECT CONVERT(DATETIME, '2018-07-19 11:59:59.999')  
    
    --- Truncate milliseconds
    --- 2018-07-19 11:59:59.000
    SELECT CONVERT(DATETIME, CONVERT(CHAR(19), '2018-07-19 11:59:59.999', 126)) 
    
    --- Current Date Time with milliseconds truncated
    SELECT CONVERT(DATETIME, CONVERT(CHAR(19), GETDATE(), 126)) 
    
    0 讨论(0)
  • 2020-12-01 09:30

    The fastest, also language safe and deterministic

    DATEADD(second, DATEDIFF(second, '20000101', getdate()), '20000101')
    
    0 讨论(0)
  • 2020-12-01 09:33
    declare @dt datetime2
    set @dt = '2019-09-04 17:24:05.784' 
    select convert(datetime2(0), @dt)
    
    0 讨论(0)
  • 2020-12-01 09:36

    This will truncate the milliseconds.

    declare @X datetime
    set @X = '2012-01-25 17:24:05.784'
    select convert(datetime, convert(char(19), @X, 126))
    

    or

    select dateadd(millisecond, -datepart(millisecond, @X), @X)
    

    CAST and CONVERT
    DATEADD
    DATEPART

    0 讨论(0)
  • 2020-12-01 09:39

    so, the easiest way now is:

    select convert(datetime2(0) , getdate())

    0 讨论(0)
提交回复
热议问题