how to convert datetime to date in sql

Posted on : 15-12-2011 | By : Devi Prasad | In : SQL Server Basics

Share:

1


How to convert datetime to date in sql server

This is a very frequent question by sql server database programmers.
The answer is vey simple, Use CAST.

The below query converts the date time value returned by getdate() into date.

SELECT CAST(GETDATE() AS DATE)

The below query is using datetime value instead of getdate() function.

SELECT CAST('2011-11-11 04:31:28.307' AS DATE)

Following is more explaned piece of code:

DECLARE @vDateTime DATETIME
DECLARE @vDate DATE
SET @vDateTime = GETDATE()
SET @vDate = CAST(@vDateTime as DATE)
SELECT @vDateTime DATETIME,@vDate DATE

The variable @vDateTime contains datetime and the variable @vdate contains the date extracted from the first variable.

Alternate ways to convert datetime to date:

Using CONVERT.

SELECT CONVERT(DATE,GETDATE())
SELECT CONVERT(DATE,'2011-11-11 04:31:28.307')

USING DATEADD AND DATEDIFF

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

USING CONVERT AND varchar

SELECT CONVERT(varchar(10),GETDATE(),102)

USING CAST AND INT

SELECT cast(cast(( GETDATE() - 0.500000038580247) as int) as datetime) 

USING CONVERT AND CHAR

SELECT CONVERT(CHAR(10),GETDATE(),103) 

USING CAST AND FLOOR

SELECT CAST(FLOOR(CAST(GETDATE() AS float)) AS datetime)

USING REPLACE AND CONVERT

SELECT REPLACE(CONVERT(VARCHAR, GETDATE(),3),'/','-')

Use alternate ways given above for SQL SERVER 2000 and SQL SERVER 2005.
All the methods shown above work in SQL SERVER 2008.

(Visited 456 times, 1 visits today)



References : Devi Prasad (sqlserverlearner.com)

Need Help On SQL Server?

Cannot Find Solution to your problem (or) If you are looking for some help on SQL Server. Dont worry Click Here to Post your question and solve your issue.


Do you like my blog?

If you liked reading this blog, please help spread the word by sharing this blog with your friends.




Comments (1)

‘ how to convert datetime to date in sql’ thread was really handy search. thanks for the post

Write a comment



Tags: , , , , , , , , , , , , , , , , , , , , , , , , , ,