Showing posts with label DATEPART. Show all posts
Showing posts with label DATEPART. Show all posts

Thursday, April 12, 2007


Getting Date part only from SQL DateTime Value

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

SELECT CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)

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

SELECT CONVERT(NVARCHAR(20), GETDATE(), 101)

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.