Rounding a datetime value down to the nearest half hour

前端 未结 6 572
再見小時候
再見小時候 2021-01-11 13:11

I have a requirement to round a datetime2 value down to the nearest half hour. For example \'10/17/2013 12:10:00.123\' would round down to \'10/17/2013 12:00:00.0\' And \'10

6条回答
  •  囚心锁ツ
    2021-01-11 14:06

    Here is a slightly different approach that I used when I needed to round down to the nearest 5 minute interval. There is probably a way to simplify this further, but at least this got me what I needed.

    DECLARE @now datetime = GETDATE()
    
    SELECT @now as cur_datetime, DATEADD(MINUTE, -(DATEDIFF(MINUTE,DATEADD(HOUR,DATEDIFF(HOUR,0,@now), 0),DATEADD(MINUTE,DATEDIFF(MINUTE,0,@now), 0)) % 5), DATEADD(MINUTE,DATEDIFF(MINUTE,0,@now), 0)) as round_down_to_nearest_5_minute_mark
    

提交回复
热议问题