Search

Saturday, December 3, 2011

How to get rid of the time part from the date returned by GETDATE function?

There are various ways you can get Date only from DateTime.


You can use DATEPARTfunction to get Date only 


SELECT LTRIM(RTRIM(STR(DATEPART(YY, GETDATE())))) + '-' + LTRIM(RTRIM(STR(DATEPART(M, GETDATE())))) + '-' + LTRIM(RTRIM(STR(DATEPART(D, GETDATE()))))

You can use Convert Function. It is better than above.
You have to use the CONVERT function to strip the time off the date. Any of the following commands will do this:

SELECT CONVERT(char,GETDATE(),101)
SELECT CONVERT(char,GETDATE(),102)
SELECT CONVERT(char,GETDATE(),103)
SELECT CONVERT(char,GETDATE(),1)




See SQL Server Books Online for more information on CONVERT function.

You can also do like this

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

If you do not want 
thetimepart at all better declare the column as smalldatetime



No comments:

Post a Comment