Как в sql запросе убрать время из даты

от admin

Как в sql запросе убрать время из даты

The TRUNC (date) function returns date with the time portion of the day truncated to the unit specified by the format model fmt . This function is not sensitive to the NLS_CALENDAR session parameter. It operates according to the rules of the Gregorian calendar. The value returned is always of data type DATE , even if you specify a different datetime data type for date . If you omit fmt , then the default format model ‘ DD ‘ is used and the value returned is date truncated to the day with a time of midnight. Refer to «ROUND and TRUNC Date Functions» for the permitted format models to use in fmt .

The following example truncates a date:

Formatting Dates using TRUNC: Examples

In the following example, the TRUNC function returns the input date with the time portion of the day truncated as specified in the format model:

In the following example, the input date values are truncated and the TO_CHAR function is used to obtain the minute component of the truncated date values:

The following statement alters the date format for the current session:

In the following example, the data is displayed in the new date format:

View and run related examples on Oracle Live SQL at Formatting Dates Using TRUNC

how to remove time from datetime

The field DATE in the database has the following format:

I would like to remove the time from the date and return the date like this:

10 Answers 10

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:

SQL-Server 2005 and Earlier

SQLite

Oracle

Postgresql

Читать:
Как ремонтировать компьютеры компак если не включаются

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.

MS SQL Server: Убираем время из значения типа datetime

Этот текст является в какой то мере переводом топика Kevin Jones — Removing time from SQL datetime, так что если вы хорошо знаете английский, то лучше, наверное, читать руководство из первых рук. Правда, мой вариант дополнен некоторыми тестами.

Итак, мы довольно часто используем SQL сервер для хранения данных с типом дата и время. В SQL Server 2005/2000 существуют два типа данных (специальных типов данных) для хранения даты и времени – это datetime и smalldatetime, разница между ними в возможностях хранения (от и до), точности времени и, соответственно, в количестве используемой памяти. В SQL Server 2008 появились дополнительные типы данных, такие как datetime2, time, date, datetimeoffset, о них вы можете прочитать в статье на MSDN — Типы данных и функции даты и времени (Transact-SQL).

TRUNC ФУНКЦИЯ (ДЛЯ ДАТ)

Oracle/PLSQL функция TRUNC возвращает дату, усеченную к определенной единице измерения.

Синтаксис

Синтаксис Oracle/PLSQL функции TRUNC:

Параметры или аргументы

date дата для усечения.

format единица измерения, которая применяется для усечения. Если параметр format опущен, функция TRUNC обрежет дату до значения дня, так что любые часы, минуты, или секунды будут усечены. Ниже приведены допустимые параметры format :

Unit Действительные параметры формата
Год SYYYY, YYYY, YEAR, SYEAR, YYY, YY, Y
ISO год IYYY, IY, I
Квартал Q
Месяц MONTH, MON, MM, RM
Неделя WW
IW IW
W W
День DDD, DD, J
День начала недели DAY, DY, D
Час HH, HH12, HH24
Минута MI

Функция TRUNC (применительно к датам) возвращает значение date.

Применение

Функцию TRUNC можно использовать в следующих версиях Oracle/PLSQL:

  • Oracle 12c, Oracle 11g, Oracle 10g, Oracle 9i, Oracle 8i

Пример для дат

Рассмотрим несколько примеров функции TRUNC и изучим, как использовать функцию TRUNC в Oracle/PLSQL.

Похожие статьи