Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding datetime to quarter minutes

I have a function to round a datetime to the nearest quarter hour. But is there a method to round down to the nearest quarter instead?

Example.

08:14:00 becomes 08:00:00
08:03:00 becomes 08:00:00
08:29:00 becomes 08:15:00 
08:55:00 becomes 08:45:00

This is what I have now to round to the nearest quarter.

(
@dt datetime
)
returns datetime
as
begin
declare @result datetime
declare @mm int
set @mm=datepart(minute,@dt)
set @result = dateadd(minute,-@mm + (round(@mm/cast(15 as float),0)*15) , @dt )

return @result
like image 957
Bladefreak Avatar asked Oct 23 '25 16:10

Bladefreak


1 Answers

Using SQL Server:

select cast( 
         FLOOR( cast( GetDate() as float)*(24*4)) / (24*4) 
       as smalldatetime) AS "datetime_quarter"

The strategy is:

  • Convert the date to a float number, *24 to get number of hours, *4 to get number of quarters
  • Round down with FLOOR
  • Convert back to number of days by /(24*4)
  • Convert number of days to a datetime. smalldatetime is used to avoid float rounding issues.

This can easily be adjusted to use ROUNDor CEILING instead; or to use other hour multiples instead of 4 (quarters).

like image 120
Daniel Reis Avatar answered Oct 27 '25 02:10

Daniel Reis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!