May 13, 2010

Converting Time in DATETIME to Zero

The biggest question I get in regards to date functions is a quick way to convert the time portion of datetime to zero (or 00:00:00), regardless of where you get the date.
There are several options out there, but the easiest to implement and remember for me is using, what I call a flip-flop.
First you date the date and convert into an float. This turns your date into a Julian date which does not have any time factors.
EX: Convert(float,getdate())
returns 40239 (Where the date is 03/04/2010).
Now to get the time back we simply convert back to a DATETIME. Using FLOOR will force it to the current day instead of potentially rounding to the next day.
Here is the code. You are welcome to use, just replace GETDATE() with your date attribute.


CONVERT
(DATETIME,(FLOOR(CONVERT(float,getdate()))))


** Updated 5.13.2010 **
As I was pondering the mysteries of the SQLverse I was looking at other ways to manipulate the dates and thought of another quick way to reset the time variant of DATETIME to 00:00:00. Of course we all know ways and some are very long. But here is another quick and dirty converion that would eliminate errors in rounding.


CONVERT
(DATETIME,CONVERT(VARCHAR,date variable,101));

This simply removes the time variable with the VARCHAR,..,101 to YYYMMDD format. Since there is no longer a time variable the DATETIME conversion can only add 00:00:00 to the time aspect.


SQL 2012 and up

Since the release of SQL 2102 and up this conversion has become quite simple. There are now at least two ways to convert a date and time variable to show no time variable. First is a type conversion. If you want to see the time but in a 00:00.0000 way I convert the DATETIME attribute to a DATE and then back, like so: CONVERT(DATETIME,CONVERT(DATE,GETDATE())) Second is using FORMAT, like so: FORMAT(GETDATE, "MM/dd/yyyy") ** In SQL, if the answer seems too complicated, it probably is.