Truncate date to only hour / minute

2019-03-11 00:12发布

问题:

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 2012-01-02 12:04:00.000 (hour and minute level)

回答1:

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)


回答2:

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)


回答3:

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.