How to Round a Time in T-SQL

前端 未结 2 449
小鲜肉
小鲜肉 2020-11-27 16:42

I\'me looking for a function that would receive a time and would round it to the next/previous hour / half-hour / quarter / minute.

相关标签:
2条回答
  • 2020-11-27 17:23

    Try this function

    CREATE FUNCTION [dbo].[RoundTime] (@Time datetime, @RoundTo float)
    RETURNS datetime
    AS
    BEGIN
       DECLARE @RoundedTime smalldatetime
       DECLARE @Multiplier float
    
       SET @Multiplier= 24.0/@RoundTo
    
       SET @RoundedTime= ROUND(CAST(CAST(CONVERT(varchar,@Time,121) AS datetime) AS float) * @Multiplier,0)/@Multiplier
    
       RETURN @RoundedTime
    END
    
    
    
    select dbo.roundtime('13:15',0.5)
    

    The 1st param is the time to be rounded and the 2nd will be base on your list (0.5-half hour, 1-one hour, ...)

    0 讨论(0)
  • 2020-11-27 17:28

    Very nice thanks. I used it in-line to round to 15 minutes

    convert(smalldatetime,ROUND(cast(TDatalog.Time as float) * (24/.25),0)/(24/.25)) AS RoundedTime
    
    0 讨论(0)
提交回复
热议问题