Truncate date to only hour / minute

后端 未结 3 1520
死守一世寂寞
死守一世寂寞 2021-02-02 09:39

How do i trunc the date in sql server 2008 like this :

I have 2012-01-02 12:04:11.443 and I want only to select 2012-01-02 12:00:00.000 and

相关标签:
3条回答
  • 2021-02-02 10:10

    This seems to work:

    select [Rounded Time] =
        dateadd(mi,datediff(mi,0,dateadd(ss,30,a.DT)),0)
    
    from
        (
        select dt = convert(datetime,'8:24:29.997')
        union all
        select dt = convert(datetime,'8:24:30.000')
        ) a
    

    Results:

    Rounded Time                                           
    ------------------------------------------------------ 
    1900-01-01 08:24:00.000
    1900-01-01 08:25:00.000
    
    (2 row(s) affected)
    
    0 讨论(0)
  • 2021-02-02 10:17
    declare @D as datetime = '2012-01-02T12:04:11.443'
    
    select dateadd(hour, datediff(hour, 0, @D), 0)
    select dateadd(minute, datediff(minute, 0, @D), 0)
    
    0 讨论(0)
  • 2021-02-02 10:31

    I'm using something like this:

    DATEADD(hour,DATEDIFF(hour,'2000-01-01 00:00',[timestamp]),'2000-01-01 00:00')
    

    You can use this formula to truncate to other levels, ie minutes:

    DATEADD(minutes,DATEDIFF(minutes,'2000-01-01 00:00',[timestamp]),'2000-01-01 00:00')
    

    You must remember that if you are truncating to seconds level, the maximum difference between the base date and [timestamp] is 68 years.

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