how to remove time from datetime in sql code example

Example: 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.

Tags:

Sql Example