Как поменять формат даты в sql

от admin

Change date format to dd/mm/yyyy in sql

I have a table called users and In sql the format of date is yyyy-mm-dd there fore when I try to enter data from my website in dd/mm/yyyy format it just enters 0000—00-00 How do I change the format it sql?

user3051827's user avatar

5 Answers 5

SQL Server Example

Or try putting your column name in place of «datecolumn»

in SQL Server, according to the article here

armen's user avatar

No Idea what data getting entered as 0000-00-00 and where zeros coming from , but this may help: Basically , Data in a Date column in Oracle can be stored in any user defined format or kept as default. It all depends on NLS parameter.

Current format can be seen by : SELECT SYSDATE FROM DUAL;

If you try to insert a record and insert statement is NOT in THIS format then it will give : ORA-01843 : not a valid month error. So first change the database date format before insert statements ( I am assuming you have bulk load of insert statements) and then execute insert script.

Format can be changed by : ALTER SESSION SET nls_date_format = ‘mm/dd/yyyy hh24:mi:ss’;

Also You can Change NLS settings from SQL Developer GUI , (Tools > preference> database > NLS)

Функция DATE_FORMAT

Функция DATE_FORMAT преобразует дату из формата год-месяц-день или формата год-месяц-день часы:минуты:секунды в другой удобный нам формат.

К примеру, из год-месяц-день можно сделать день.месяц.год или месяц—год

См. также функцию TIME_FORMAT, которая меняет формат вывода времени.

Синтаксис

Команды

Можно использовать следующие команды, чтобы сделать нужный формат вывода:

Команда Описание
%d День месяца, число от 00 до 31.
%e День месяца, число от 0 до 31.
%m Месяц, число от 01 до 12.
%c Месяц, число от 1 до 12.
%Y Год, число, 4 цифры.
%y Год, число, 2 цифры.
%j День года, число от 001 до 366.
%H Час, число от 00 до 23.
%k Час, число от 0 до 23.
%h Час, число от 01 до 12.
%I Час, число от 01 до 12.
%l Час, число от 1 до 12.
%i Минуты, число от 00 до 59.
%S Секунды, число от 00 до 59.
%s Секунды, число от 00 до 59.
%w День недели (0 — воскресенье, 1 — понедельник).
%W Название дня недели по-английски.
%a Сокращенный день недели по-английски.
%M Название месяца по-английски.
%b Сокращенный месяц по-английски.
%D День месяца с английским суффиксом (1st, 2nd, 3rd и т.д.).
%r Время, 12-часовой формат (hh:mm:ss [AP]M).
%T Время, 24-часовой формат (hh:mm:ss).
%p AM или PM.
%U Неделя, где воскресенье считается первым днем недели, число от 00 до 53.
%u Неделя, где понедельник считается первым днем недели, число от 00 до 53.
%V Неделя, где воскресенье считается первым днем недели, число от 01 до 53.
Используется с `%X’.
%v Неделя, где понедельник считается первым днем недели, число от 01 до 53.
Используется с `%x’.
%X Год для недели, где воскресенье считается первым днем недели, число, 4 цифры.
Используется с ‘%V’.
%x Год для недели, где воскресенье считается первым днем недели, число, 4 разряда.
Используется с ‘%v’.
%% Символ `%’.

Примеры

Все примеры будут по этой таблице workers, если не сказано иное:

id
айди
name
имя
date
дата регистрации
1 Дима 2010-03-01 12:01:02
2 Петя 2011-04-02 13:02:03
3 Вася 2012-05-03 14:03:04

Пример

В данном примере при выборке создается новое поле, в котором будет лежать дата в другом формате:

SQL Date Format Explained with Examples

In this article, you will learn how to format date and time values using SQL Statements. There are more than 50 SQL Date Formats that can be used in different versions of SQL Server, MySQL, and other database management systems. Apart from SQL Date Formats, Wikipedia provides a lengthy list of SQL date formats used in different parts of the world. For example in the United States, a unique date format ‘mm-dd-yyyy’ is being used. Some nations, such as Korea, Iran, and China, write the year first and the day last (yyyy-mm-dd). (MIT)

This different Date interpretation varies between different countries. Suppose you have stored the ’01-05-1979′ date in your SQL database. SQL Server and MySQL have their specific Date formats. On retrieval of this date can communicate different meanings to different peoples across the globe.

Hence for a database programmer and a user, SQL Date Format is very much necessary to learn. In this article, we will try to enlist and outline the details of all SQL Date Formats used in SQL Server and MySQL with east and practical examples.

As you have already learned, various SQL Date Functions and SQL Time Functions articles about the different functions like FORMAT() and CONVERT() can be used to format Date in a specific way.

Types of MS SQL Server Date Formats

MS SQL Server provides Six different data types for manipulating Date and Time values. Similarly, you can SQL Server Convert Date Formats.

Data Types SQL Date Format Example
Time hh:mm:ss[.nnnnnnn] 12:36:30.1231231
Date YYYY-MM-DD 1979-05-01
SmallDateTime YYYY-MM-DD hh:mm:ss 1979-05-01 12:36:30
DateTime YYYY-MM-DD hh:mm:ss[.nnn] 1979-05-01 12:36:30.123
DateTime2 YYYY-MM-DD hh:mm:ss[.nnnnnnn] 1979-05-01 12:36:30.1231231
DateTimeOffset YYYY-MM-DD hh:mm:ss[.nnnnnnn] [+|-]hh:mm 1979-05-01 12:36:30.1231231 + 05:30

Let run this SELECT statement on MS SQL SEVER to verify the above SQL Date formats in SQL SERVER. In this query, we have used GETDATE() and SYSDATETIME() SQL Functions to get the current DateTime value. The SQL Date and Time Functions GETUTCDATE() and SYSUTCDATETIME() functions are used

SAMPLE OUTPUT

SQL Date Formats in MS SQL SERVER - Convert and Format

SQL Date Formats in SQL SERVER — Sample output 1

Use of FORMAT() Function in SQL Date Formats

Let’s start explaining the use of FORMAT() Microsoft SQL Server Function for formatting the dates and times. Before MS SQL SERVER 2008 version, the CONVERT() Function was to perform all SQL Date Formats and to convert from one Date Format to other. We will also explain the use of CAST() and CONVERT() for SQL Date convert and format options in this article. After learning the syntax, you will be demonstrated a list of the available SQL examples on how to use the CONVERT() SQL Server function to handle different SQL SERVER Date formats in a database.

Syntax of FORMAT() Function

In, MS SQL SERVER 2012, the FORMAT() function is introduced for handling the conversion of SQL Date Formats. You do not need to remember the default SQL DateTime Format Numbers to convert a date from one specific format to another in the FORMAT() function.

The syntax of the SQL Server FORMAT function is the following:

  • value: must be an expression or value that belongs to any supported DateTime data type.
  • format:can be a nvarchar format pattern containing a valid format string. It can be a customer pattern supported characters for dates and numeric values.
  • culture: An optional nvarchar argument specifying a culture. If the culture argument is not provided, the language of the current session is used. This language is set either implicitly, or explicitly by using the SET LANGUAGE statement. culture accepts any culture supported by the .NET Framework as an argument; it is not limited to the languages explicitly supported by SQL Server. If the culture argument is not valid, FORMAT raises an error. For getting the list of culture, you can visit Wikipedia for ISO 639-1, ISO 3166-1 alpha-2.

Different types of supported date formats

Here is the table which shows the list of supported dates characters with their range and expected output values:

Format Range/Output
dd 01-31
MM 01-12
yy 00-99
HH 00-23
mm 00-59
ss 00-59
tt AM or PM
dddd Day Name e.g. Monday
MMM Abbreviated Month Name e.g. JAN, FEB
MMMM Full Month Name
yyyy four digit year
d 1-31
ud US Culture

Example-1 | SQL Date Format with the FORMAT() Function

Now is the perfect time to work with SQL Date formats examples with the FORMAT() functions. In all the below examples, We will use Use the FORMAT() SQL Function to mentioning Different SQL Date Formats. We will use the GETDATE() function to get the DateTime value and will use CUSTOM Format String. In this SELECT Statement, we will use only two arguments (value, and format_string).

In this SELECT Query to convert and format the DECLARE @datetimevalue ‘ 01/05/1979 ‘, we have used a Custom Format string. You can see that no SQL Date Format number is being used as it was being used in the CONVERT() SQL DATE Format Function. Six different format_strings have been mentioned in every FORMAT() function with same the @datetimevalue = '01/05/1979' .

SAMPLE OUTPUT

SQL SERVER DATE FORMATS with FORMAT() Function

SQL SERVER DATE FORMATS with FORMAT() Function — Sample Output 2

SQL Server Date FORMAT with Culture

The Culture is an optional argument that can be used for SQL Date convert and format. With the culture argument, we can get SQL Date Formats for different regions. As Format() function is very rich in syntax and arguments and can be used with all data types supported by .NET and SQL Server. Hence we have a lengthy list of culture codes to use with FORMAT SQL Date Format and Convert function.

Example-2 | Use of Culture with SQL Date Format()

Here is another example of the SELECT Statement that will use the culture argument in the FORMAT() function. You will see how simple it will be to get the required SQL Date Format for a specific region. For example, you want to convert the DateTime value into US English, Norwegian, Zulu, and Indian-Hindi format. We will use only their culture code from the above-mentioned list as under

SAMPLE OUTPUT

SQL SERVER DATE FORMATS with FORMAT() and Culture argument

Use of FORMAT() Function with culture — Sample output 3

CAST and CONVERT() Date Format Function

Microsoft SQL Server 2008 and earlier versions used this CONVERT() SQL function to format dates in SQL queries and other SQL procedures. These functions convert an expression of one data type to another. Hence these SQL functions can also be used to Format SQL Dates. The CAST() and The CONVERT() function can convert a value (of any type) into a specified datatype.

As far as SQL Date Formatting is concerned, the FORMAT() function is a much better choice as compared to the CONVERT() SQL function. It is not very flexible and provides limited date formats and styles in contrast to the SQL FORMAT() function for date formatting.

SQL Server Date and Time styles

SQL Date Formats/styles are mentioned in the official documentation with the help of a table consisting of more than 40 different date formats. For a date or time data type expression, style can have one of the values shown in the following table. It is not be mentioned here that CAST() SQL Function can convert/format a SQL date format to any other datatype but cannot use these styles.

Syntax of CAST() / CONVERT()

In both these syntax, the expression means the data type which you need to format or convert a SQL DateTime value. You can observe in both The CAST() and CONVERT() expression and data_type(length) parameters are being indifferent sequences. The CONVERT SQL Function contains an extra parameter style which can be chosen from the above-mentioned table from the official documentation.

Here is a smaller snapshot of this table.

SQL Date format Styles in SQL Server

SQL Date format Styles in SQL Server | Figure 1

Example-3 | Use of CONVERT() for SQL Server DATE Formats

In this code you can see that we are using two styles USA and ANSI in the CONVERT() SQL Server Function with the help of Style parameter values 101 and 102 respectively. We have used the VARCHAR data type to convert the values returned by the GETDATE() SQL Function. As shown in the above Figure 1 showing the style table, USA date style code 101 for displaying year value with century and only 1 for year value without century.

SAMPLE OUTPUT

SQL Date Foramt with CONVERT() Functions - Output

SQL Date Format with CONVERT() — Sample Output 4

In the output, you can see the style values from figure 1 are correctly producing the output. In these, all examples USA style value is used in different ways with Date and Datetime target format.

Example-4 | Use of CAST() for SQL Server DATE Formats

The CAST() SQL Function is used to convert a data type into another data type. Here in this example, we will use the CAST() SQL Function to convert a DateTime value returned by GETDATE() function into varchar, DateTime, date, and time data types.

SAMPLE OUTPUT

SQL Date Format with CAST() Function - Sample output 5

SQL Date Format with CAST() Function — Sample output 5

In the sample output of this example, you can see that

  • The first column GETDATE() value is converted to varchar
  • Second column GETDATE() value is converted into DateTime
  • Third column GETDATE() value is converted in only the Date
  • Fourth column GETDATE() value is converted in only the Time

Example-5 | Use of Long SQL Date Formats with CONVERT()

In most parts of the world, a long-date format is being used. For example in Europe, the Following «DD MMM YYYY HH:MM:SS: MMM» long date format is used. In the United States, this «USA with Time AM/PM» long date format is also used. ISO uses this long-date format «YYYY-MM-DDTHH:MM: SS.mmm».

In this example, we will use see how the CONVERT() function can be used with Style code from the official SQL Date FORMAT Styles table to format SQL dates in the above-mentioned date formats.

SAMPLE OUTPUT

sql date - Date_Format() example 5

SQL Date Format | Example 5 output

Example-6 | Use of DATEADD() with CONVERT() and CAST()

In this example, we will see that DATADD() SQL Function can be used with CAST() and CONVERT() date functions to add and subtract date with new formats. As you know that, DATEADD() SQL Server function can add/subtract year, month, or day values from the given DateTime value. In this code, we will get the current date using the GETDATE() Function and then will add and subject 1 year. We will use short date format 107 from the style table.

SAMPLE OUTPUT

SQL DATE Convert Foramt with DATEADD Example 6

SQL DATE Convert Format with DATEADD | Example Output

Summary

In this article, we learned about SQL Date Formats and how to use FORMAT() , CAST() and CONVERT() SQL Functions. Different date formats have been reported by Wikipedia in different parts of the world. Hence, SQL Server and other DBMS have made it possible to covert and format the SQL Date using different built-in SQL Date Format and CONVERT Functions.

In earlier versions of Microsoft SQL SEVER, CONVERT() SQL Function was used with a pre-defined list of SQL Date Format and styles. In, MS SQL SERVER 2012 and higher, the FORMAT() function is introduced for handling the conversion and formatting of SQL Date Formats. You do not need to remember the default SQL DateTime Format Numbers to convert a date from one specific format to another in the FORMAT() function.

References

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Microsoft SQL Server
Даты

Округление данных datetime. Дробные значения секунды. Точность datetime округляется до приращений .000, .003 или .007 секунд, как показано в следующей таблице.

Пользовательское значение Системное сохраненное значение
01/01/98 23: 59: 59.999 1998-01-02 00: 00: 00.000
—— ——
01/01/98 23: 59: 59.995 1998-01-01 23: 59: 59.997
01/01/98 23: 59: 59.996
01/01/98 23: 59: 59.997
01/01/98 23: 59: 59.998
—— ——
01/01/98 23: 59: 59.992 1998-01-01 23: 59: 59.993
01/01/98 23: 59: 59.993
01/01/98 23: 59: 59.994
—— ——
01/01/98 23: 59: 59.990 1998-01-01 23: 59: 59.990
01/01/98 23: 59: 59.991
—— ——

Если требуется более высокая точность, следует использовать time , datetime2 или datetimeoffset .

Форматирование даты и времени с использованием CONVERT

Вы можете использовать функцию CONVERT для приведения типа данных datetime в форматированную строку.

Вы можете также использовать некоторые встроенные коды для преобразования в определенный формат. Вот варианты, встроенные в SQL Server:

@convert_code Результат
100 "21 июля 2016 7:56 утра"
101 "07/21/2016"
102 "2016.07.21"
103 "21/07/2016"
104 "21.07.2016"
105 "21-07-2016"
106 «21 июля 2016 года»
107 «21 июля 2016 года»
108 «7:57:05»
109 "21 июля 2016 7: 57: 45: 707AM"
110 "07-21-2016"
111 "2016/07/21"
112 "20160721"
113 "21 июля 2016 года 07: 57: 59: 553"
114 "07: 57: 59: 553"
120 «2016-07-21 07:57:59»
121 "2016-07-21 07: 57: 59.553"
126 "2016-07-21T07: 58: 34,340"
127 "2016-07-21T07: 58: 34,340"
130 "16: 1437 7: 58: 34: 340AM"
131 "16/10/1437 7: 58: 34: 340AM"

Форматирование даты и времени с использованием FORMAT

Вы можете использовать новую функцию: FORMAT() .

Используя это, вы можете преобразовать поля DATETIME в свой собственный формат VARCHAR .

пример

Понедельник, 5 сентября 2016 года 12:01:02

аргументы

Учитывая, что формат DATETIME отформатирован, 2016-09-05 00:01:02.333 , следующий график показывает, каков будет их вывод для предоставленного аргумента.

аргументация Выход
гггг 2016
уу 16
MMMM сентябрь
М.М. 09
M 9
дддд понедельник
ддд понедельник
дд 05
d 5
HH 00
ЧАС 0
чч 12
час 12
мм 01
м 1
сс 02
s 2
тт AM
T
FFF 333
Ф.Ф. 33
е 3

Вы также можете предоставить один аргумент функции FORMAT() для генерации предварительно форматированного вывода:

Понедельник, 5 сентября 2016 года 4:01:02

Одиночный аргумент Выход
D Понедельник, 5 сентября 2016 г.
d 9/5/2016
F Понедельник, 5 сентября 2016 года 12:01:02
е Понедельник, 5 сентября 2016 года 12:01
г 5/5/2016 12:01:02
г 5/5/2016 12:01
M Сентябрь 05
О 2016-09-05T00: 01: 02,3330000
р Пн, 05 сен 2016 00:01:02 GMT
s 2016-09-05T00: 01: 02
T 12:01:02 AM
T 12:01
U Понедельник, 5 сентября 2016 года 4:01:02
U 2016-09-05 00: 01: 02Z
Y Сентябрь 2016 года

Примечание. В приведенном выше списке используется культура en-US . Для FORMAT() через третий параметр можно указать другую культуру:

Получить текущую дату

Встроенные функции GETDATE и GETUTCDATE возвращают текущую дату и время без смещения часового пояса.

Возвращаемое значение обеих функций основано на операционной системе компьютера, на котором запущен экземпляр SQL Server.

Возвращаемое значение GETDATE представляет текущее время в том же часовом поясе, что и операционная система. Возвращаемое значение GETUTCDATE представляет текущее время UTC.

Любая функция может быть включена в предложение SELECT запроса или как часть логического выражения в WHERE .

Есть еще несколько встроенных функций, которые возвращают разные варианты текущего времени:

DATEADD для добавления и вычитания периодов времени

Чтобы добавить меру времени, number должен быть положительным. Чтобы вычесть значение времени, number должно быть отрицательным.

ПРИМЕЧАНИЕ. DATEADD также принимает аббревиатуры в параметре datepart . Использование этих сокращений обычно обескураживается, поскольку они могут вводить в заблуждение ( m vs mi , ww vs w и т. Д.).

Ссылка на детали даты

Это значения datepart доступные для функций даты и времени:

DatePart Сокращения
год yy, yyyy
четверть qq, q
месяц мм, м
DayOfYear dy, y
день dd, d
неделю wk, ww
будний день dw, w
час чч
минут mi, n
второй ss, s
миллисекунды Миз
микросекунда MCS
наносекунда нс

ПРИМЕЧАНИЕ . Использование сокращений обычно обескураживается, поскольку они могут вводить в заблуждение ( m vs mi , ww vs w и т. Д.). Длинная версия представления datepart способствует ясности и удобочитаемости и должна использоваться по возможности ( month , minute , week , weekday и т. Д.).

DATEDIFF для расчета разницы во времени

Он вернет положительное число, если datetime_expr в прошлом datetime_expr2 к datetime_expr2 и отрицательное число в противном случае.

ПРИМЕЧАНИЕ. DATEDIFF также принимает аббревиатуры в параметре datepart . Использование этих сокращений обычно обескураживается, поскольку они могут вводить в заблуждение ( m vs mi , ww vs w и т. Д.).

DATEDIFF также может использоваться для определения смещения между UTC и локальным временем SQL Server. Следующий оператор можно использовать для расчета смещения между временем по Гринвичу и местным временем (включая часовой пояс).

DATEPART & DATENAME

DATEPART возвращает указанное число datepart указанного выражения datetime как числовое значение.

DATENAME возвращает строку символов, которая представляет заданную datepart в определенную дату. На практике DATENAME в основном полезен для получения названия месяца или дня недели.

Существуют также некоторые сокращенные функции для получения года, месяца или дня выражения datetime, которые ведут себя как DATEPART с их соответствующими единицами datepart .

ПРИМЕЧАНИЕ. DATEPART и DATENAME также принимают аббревиатуры в параметре datepart . Использование этих сокращений обычно обескураживается, поскольку они могут вводить в заблуждение ( m vs mi , ww vs w и т. Д.).

Получение последнего дня месяца

Используя функции DATEADD и DATEDIFF , можно вернуть последнюю дату месяца.

Функция EOMONTH обеспечивает более сжатый способ возврата последней даты месяца и имеет необязательный параметр для смещения месяца.

Вернуть только дату из DateTime

Существует много способов вернуть дату из объекта DateTime

  1. SELECT CONVERT(Date, GETDATE())
  2. SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())) возвращается 2016-07-21 00: 00: 00.000
  3. SELECT CAST(GETDATE() AS DATE)
  4. SELECT CONVERT(CHAR(10),GETDATE(),111)
  5. SELECT FORMAT(GETDATE(), 'yyyy-MM-dd')

Обратите внимание, что опции 4 и 5 возвращают строку, а не дату.

Создать функцию для расчета возраста человека на определенную дату

Эта функция будет принимать 2 параметра datetime, DOB и дату для проверки возраста на

например, чтобы проверить возраст сегодня кого-то, родившегося 1 / 1/2000

ОБЪЕКТ ПРОГРАММЫ CROSS PLATFORM

В Transact SQL вы можете определить объект как Date (или DateTime ), используя [DATEFROMPARTS][1] (или [DATETIMEFROMPARTS][1] ), например, следующую:

Параметры, которые вы предоставляете: Год, Месяц, День для функции DATEFROMPARTS а для функции DATETIMEFROMPARTS вам необходимо DATEFROMPARTS год, месяц, день, час, минуты, секунды и миллисекунды.

Эти методы полезны и заслуживают внимания, потому что использование простой строки для создания даты (или даты и времени) может привести к сбою в зависимости от настроек региона, местоположения или формата файла главной машины.

Читать:
Battery life extender что это

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