get the date from datetime in sql remove time code example

Example 1: remove time from date sql

First thing's first, if your dates are in varchar format change that, store dates as dates it will save you a lot of headaches and it is something that is best done sooner rather than later. The problem will only get worse.

Secondly, once you have a date DO NOT convert the date to a varchar! Keep it in date format and use formatting on the application side to get the required date format.

There are various methods to do this depending on your DBMS:

SQL-Server 2008 and later:

SELECT  CAST(CURRENT_TIMESTAMP AS DATE)
SQL-Server 2005 and Earlier

SELECT  DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)
SQLite

SELECT  DATE(NOW())
Oracle

SELECT  TRUNC(CURRENT_TIMESTAMP)
Postgresql

SELECT  CURRENT_TIMESTAMP::DATE
If you need to use culture specific formatting in your report you can either explicitly state the format of the receiving text box (e.g. dd/MM/yyyy), or you can set the language so that it shows the relevant date format for that language.

Either way this is much better handled outside of SQL as converting to varchar within SQL will impact any sorting you may do in your report.

If you cannot/will not change the datatype to DATETIME, then still convert it to a date within SQL (e.g. CONVERT(DATETIME, yourField)) before sending to report services and handle it as described above.

Example 2: REMOVE DATE FROM DATE TIME SQL SERVER

SELECT CONVERT(varchar(8), GETDATE(), 108) AS TimeOnly
CONVERT(VARCHAR(7),@AppDate,111) date year only

Tags:

Sql Example