Getting Date part only from SQL DateTime Value

Posted: April 12, 2007 in SQL Server
Even though I have taken date part only from a datetime field earlier I had to struggle for some minutes yesterday, so I thought why I shouldn’t put a blog entry on this so it will help me. Also I think that this will help many of you reading my blogs.

I found two ways to accomplish this without using DATEPART. I believe it is not good practice to use DATEPART and assemble the date by ourselves because it will sometimes change the original year, month and day order and at times that will cause some unnecessary problems.

Method 1


What is happening here is CAST(GETDATE() AS FLOAT) will cast the date into a floating point number {2007-04-12 22:12:00.837 = 39182.9236936343}.
Then the FLOOR function will return the largest integer part of the parameter. In our case the result of CAST(GETDATE() AS FLOAT) {39182.9236936343}. The result of this will be 39182.
Now I will caste this value again to a DATETIME value. This time, since there is no fraction part in the value that results in the time part to return as 00:00:00.000. {Fraction part represents the time.}
The final result will be 2007-04-12 00:00:00.000.

Method 2


In this second approach what I am doing is simply Converting the date into a character. The last parameter of the CONVERT function {101} is the style number which will specify the conversion. Value 101 will return the value in the format of MM/DD/YYYY. {To acquire more information about conversion styles refer CONVERT function in SQL Books Online.} The result of this will be 04/12/2007.

One thing to remember when using second method is that the result will be in the format MM/DD/YYYY. So if you are comparing this value with another date you have to be careful to make the other comparing value also in the format of MM/DD/YYYY. Otherwise it will return wrong results.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s