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?
If you are using SQL Server 2008, you can use the new
Date
datatype like this:If you still need your value to be a
DateTime
datatype, you can do this:A method that should work on all versions of SQL Server is:
This is late, but will produce the exact results requested in the post. I also feel it is much more intuitive than using dateadd, but that is my preference.
Truncated Date: 2010-03-01
Truncated DateTime: 2010-03-01 00:00:00.000
DateTime: 2010-03-01 17:34:12.017
To round to the nearest whole day, there are three approaches in wide use. The first one uses
datediff
to find the number of days since the0
datetime. The0
datetime 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
datetime
is 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_day
as 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
0
gives 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.
Try:
UPDATE: answer on the second question: for years you could use a little bit modified version of my answer:
for quarter:
and so on.
I checked, up to minutes - it's OK. But on seconds I've got an overflow message:
One more update: take a look to the following answer to the same question