Extract only the Date from DateTime in SQL Server
Normaly extarcting date only from DATETIME is commaon and serious problem in SQL SERVER.
Here i have given some common methods to extract on the date from datetime
Method 1
------------
SELECT
CAST
(
FLOOR(CAST(GETDATE() AS FLOAT))
AS DATETIME
)
Method 2--but it is not correct
------------------------------------
This is similar to first method but we have used INT instead of FLOAT . But it will seldom correct. It will not give you the exact date of what you expecting.
So better not to use INT.
SELECT
CAST
(
FLOOR(CAST(GETDATE() AS INT))
AS DATETIME
)
Method 3
----------
i would recommend this method to extract inly date though there are many methods. because this method is very simple and easy.
SELECT
CAST
(
STR(DAY(GETDATE()))+ '/' +
STR(MONTH(GETDATE())) +'/'+
STR(YEAR(GETDATE()))
AS DATETIME
)
Method 4
----------
In this we have used CONVERT function with 113 date type.
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(12), GETDATE(), 113))
Method 5
----------
Here we have used DATEDIFF and DATEADD functions together to extract.get the different between specified date and 0 then again add o with output value of DATEDIFF
SELECT DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0)
Method 6
----------
This is also similar to previous method. But here we have not used DATEADD instead we have used CAST.
SELECTCAST(DATEDIFF(dd,0,GETDATE() as datetime)
Here i have given some common methods to extract on the date from datetime
Method 1
------------
SELECT
CAST
(
FLOOR(CAST(GETDATE() AS FLOAT))
AS DATETIME
)
Method 2--but it is not correct
------------------------------------
This is similar to first method but we have used INT instead of FLOAT . But it will seldom correct. It will not give you the exact date of what you expecting.
So better not to use INT.
SELECT
CAST
(
FLOOR(CAST(GETDATE() AS INT))
AS DATETIME
)
Method 3
----------
i would recommend this method to extract inly date though there are many methods. because this method is very simple and easy.
SELECT
CAST
(
STR(DAY(GETDATE()))+ '/' +
STR(MONTH(GETDATE())) +'/'+
STR(YEAR(GETDATE()))
AS DATETIME
)
Method 4
----------
In this we have used CONVERT function with 113 date type.
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(12), GETDATE(), 113))
Method 5
----------
Here we have used DATEDIFF and DATEADD functions together to extract.get the different between specified date and 0 then again add o with output value of DATEDIFF
SELECT DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0)
Method 6
----------
This is also similar to previous method. But here we have not used DATEADD instead we have used CAST.
SELECTCAST(DATEDIFF(dd,0,GETDATE() as datetime)
Comments
Post a Comment