I would like to get datetime column rounded to nearest hour and nearest minute preferably with existing functions.
For this column value 2007-09-22 15:07:38.850, the output will look like:
2007-09-22 15:08 -- nearest minute
2007-09-22 15 -- nearest hour
will return
The above just truncates the seconds and minutes, producing the results asked for in the question. As @OMG Ponies pointed out, if you want to round up/down, then you can add half a minute or half an hour respectively, then truncate:
and you’ll get:
Before the date data type was added in SQL Server 2008, I would use the above method to truncate the time portion from a datetime to get only the date. The idea is to determine the number of days between the datetime in question and a fixed point in time (
0, which implicitly casts to1900-01-01 00:00:00.000):and then add that number of days to the fixed point in time, which gives you the original date with the time set to
00:00:00.000:or more succinctly:
Using a different datepart (e.g.
hour,mi) will work accordingly.