Reputation: 89
I have a database which one column has a hr:min:sec value like "14:04:33" as varchar (50). I want to round up/down to the nearest 5 min: 14:05:00 and 14:00:00 respectively and both of them needs to be varchar(50). I tried to round up by converting them to datetime and the code I used to round down to the nearest 5 min was:
DECLARE @Time varchar (50)
SELECT @Time ='14:04:33'
SELECT CAST(CONVERT(datetime,(FLOOR(CAST(CONVERT(datetime,@Time,108)As float )*288)/288), 108)AS varchar (50))
however the final output is Jan 1 1900 2:00 PM
and the code I used to round up to the nearest 5 min was:
DECLARE @Time varchar (50)
SELECT @Time ='14:04:33'
SELECT CAST(CONVERT(datetime,(CEILING(CAST(CONVERT(datetime,@Time,108)As float)*288)/288), 108) AS varchar(50))
And the final output is Jan 1 1900 2:05 PM. I am looking for a suitable function for conversion in sql server 2012.
Upvotes: 0
Views: 4238
Reputation: 5999
If you're on SQL 2012, you can use the new date & time functions. This way will round down to the nearest 5 minutes:
DECLARE @When VARCHAR(50) = '14:22:33'
DECLARE @Time TIME = CAST(@When AS TIME)
SELECT TIMEFROMPARTS
(
DATEPART(HOUR, @Time), --Hour
DATEPART(MINUTE, @Time) / 5 * 5, --Minute
0, --Second
0, --Fraction
0 --Precision
)
http://msdn.microsoft.com/en-us/library/ms186724.aspx
Upvotes: 0
Reputation: 13496
try this:
Floor Value --
DECLARE @Time varchar (50)
SELECT @Time ='14:04:33'
SELECT CONVERT(time,CONVERT(varchar(2),DATEPART(HH,@Time))+':'+CONVERT(varchar(2),(DATEPART(MI,@Time)-DATEPART(MI,@Time)%5))+':00')
Ceil Value --
DECLARE @Time varchar (50)
SELECT @Time ='14:04:33'
SELECT DATEADD(MI,5,CONVERT(time,CONVERT(varchar(2),DATEPART(HH,@Time))+':'+CONVERT(varchar(2),(DATEPART(MI,@Time)-DATEPART(MI,@Time)%5))+':00'))
Upvotes: 2