Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding a datetime value down to the nearest half hour

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/17/2013 12:34:17.123' would round down to 10/17/2013 12:30:00.0'. My first thought was to create a UDF which would break the date and time apart and do it that way. However, I'm wondering if something like this can be done in a single T-SQL statement?

I'm using SQL Server 2012 and the data type of the column is a dateTime2 (which cannot be converted to a float!!)

like image 567
Hosea146 Avatar asked Oct 17 '13 13:10

Hosea146


3 Answers

Here is one way to do it:

update t set
  d = dateadd(minute,datediff(minute,'19000101',d)/30*30,'19000101');
like image 196
Steve Kass Avatar answered Oct 16 '22 17:10

Steve Kass


The answer by Ian is good, but it contains an unnecessary conversion. I suggest

SELECT CONVERT(smalldatetime, ROUND(CAST([columnname] AS float) * 48.0,0,1)/48.0) FROM [tableName]

If you want to round to the nearest half-hour instead of always rounding down, use

SELECT CONVERT(smalldatetime, ROUND(CAST([columnname] AS float) * 48.0,0)/48.0) FROM [tableName]
like image 16
Twinkles Avatar answered Oct 16 '22 17:10

Twinkles


How about this

declare @d datetime = '2013-05-06 12:29.123'
select 
case 
    when datepart(minute, @d) < 30 then cast(dateadd(minute, -datepart(minute,@d)-datepart(second,@d), @d) as smalldatetime)
    when datepart(minute, @d) >= 30 then cast(dateadd(minute, -datepart(minute,@d)-datepart(second,@d)+30, @d) as smalldatetime)
end
like image 1
Andrew Avatar answered Oct 16 '22 15:10

Andrew