Link to home
Start Free TrialLog in
Avatar of NerishaB
NerishaBFlag for South Africa

asked on

SQL - Rounding datetime to the nearest hour

Hi,

How would I round myu field "ClockTime" to the nearest hour?

So if I had 08:12:34, it must be rounded to 08:00:00
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

dateadd(second, - datepart(second, ClockTime),  dateadd(minute, - datepart(minute, ClockTime), ClockTime) )
Avatar of NerishaB

ASKER

is there a way to do this without creating a function?
YOU MAY TRY:-

SELECT   DATEADD(Hour, DATEDIFF(Hour, 0, GETDATE()), 0)

Open in new window



REPLACE GETDATE() HERE WITH YOUR DATETIME.
ASKER CERTIFIED SOLUTION
Avatar of mayank_joshi
mayank_joshi
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
further if you only want the time part:-
SELECT     RIGHT(DATEADD(Hour, DATEDIFF(Hour, 0, '08:12:34'), 0), 7)

Open in new window

Thanks
another method for getting only time:-

select CONVERT(varchar(8),DATEADD(Hour, DATEDIFF(Hour, 0, '08:12:34'), 0),108)

Open in new window