If I have a date value like 2010-03-01 17:34:12.018
What is the most efficient way to turn this into 2010-03-01 00:00:00.000?
As a secondary question, what is the best way to emulate Oracle’s TRUNC function, which will allow you to truncate at Year, Quarter, Month, Week, Day, Hour, Minute, and Second boundaries?
To round to the nearest whole day, there are three approaches in wide use. The first one uses
datediffto find the number of days since the0datetime. The0datetime corresponds to the 1st of January, 1900. By adding the day difference to the start date, you’ve rounded to a whole day;The second method is text based: it truncates the text description with
varchar(10), leaving only the date part:The third method uses the fact that a
datetimeis really a floating point representing the number of days since 1900. So by rounding it to a whole number, for example usingfloor, you get the start of the day:To answer your second question, the start of the week is trickier. One way is to subtract the day-of-the-week:
This returns a time part too, so you’d have to combine it with one of the time-stripping methods to get to the first date. For example, with
@start_of_dayas a variable for readability:The start of the year, month, hour and minute still work with the “difference since 1900” approach:
Rounding by second requires a different approach, since the number of seconds since
0gives an overflow. One way around that is using the start of the day, instead of 1900, as a reference date:To round by 5 minutes, adjust the minute rounding method. Take the quotient of the minute difference, for example using
/5*5:This works for quarters and half hours as well.