Archive

Posts Tagged ‘t-sql’

T-SQL Snippet: Strip Time from Datetime

January 15th, 2010
Comments Off

I would have thought that this would be fairly common knowledge but I am often asked for a quick example of how to strip off the time element of a SQL datetime type. So, here is an example followed by an explanation of how and why it works:

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

Technically, this doesn’t strip the time but instead sets it to midnight of current date. So, what is this snippet doing? To start we need to know a little bit about how datetime is stored in SQL Server. The datetime type is an 8 byte type. Essentially, it is stored as two distinct 4 byte integers. The first 4 byte integer represents the number of days since the base date for SQL Server. The base date for the datetime type is 01/01/1900. The second 4 byte integer that represents the milliseconds since midnight.

With that in mind, the following snippet should return this base date:

SELECT CAST(0 as datetime)

Now, back to dissecting the original snippet, I am using the built-in DATEDIFF function to return an integer. The integer is the number of days that have elapsed since the base date of 01/01/1900. With the knowledge of how a datetime is stored you might be tempted to just CAST directly from the datetime to an int. However, depending on the time of day, it might cause the int to round up. So, it is better to just rely on the DATEDIFF.

Finally, to convert this integer back to a datetime type I am using the DATEADD function. Once again, we are using the base date and adding the integer to it to give us today’s date with a midnight time component. Pretty simple, right?

Author: Pierre LaFromboise Categories: Blog Tags: