the date format in mySQL have type (yyyy-mm-dd), now I try to reverse it (dd-mm-yyyy).
I got table user
CREATE TABLE USER
(
USER_ID INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY,
DOB DATE,
);
so when i insert value into that:
INSERT INTO USER(DOB) VALUES(DATE_FORMAT('13-07-1990','%d,%m,%Y));
however, it does not work. It notice that I should use 1990-07-13 instead of ’13-07-1990′.
please help me to do that. Thanks.
asked Nov 17, 2013 at 18:32
6
The ANSI SQL standard format for date is YYYY-MM-DD HH:MM:SS
. It’s easier to capture the date in this format for insertion into a database.
In order to store the date with the format you’re using (MM-DD-YYYY
) you need to use the STR_TO_DATE
function which allows you to convert a string to a date. The syntax for this function is:
STR_TO_DATE(str, format)
The specifiers for the format can be found here.
For your INSERT
statement, you would use:
INSERT INTO `user` (`dob`) VALUES
( STR_TO_DATE('13-07-1990','%d-%m-%Y') )
answered Nov 17, 2013 at 18:35
KermitKermit
33.5k13 gold badges83 silver badges120 bronze badges
4
DATE_FORMAT
is only used to save dates into varchar fields with non-standard formats or to retrieve them from the DB in a non-standard format. You may NOT save something in a DATE
type field as any format besides YYYY-MM-DD.
answered Nov 17, 2013 at 18:38
DevlshOneDevlshOne
8,3171 gold badge28 silver badges37 bronze badges
FROM THE DOCS : The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in ‘YYYY-MM-DD’ format. The supported range is ‘1000-01-01’ to ‘9999-12-31’.
My Way would be a little different.I would compute my date in php and pass the desired format to the query rather than computing it in query.
$your_date= "2010-03-21";
$desired_format = date("d-m-Y", strtotime($your_date));//returns 21-03-2010
$desired_format = date("m-d-Y", strtotime($your_date));//returns 03-21-2010
by using strtotime and date function,You can convert your date in to any format you desire
answered Nov 17, 2013 at 19:37
HIRA THAKURHIRA THAKUR
16.9k14 gold badges53 silver badges86 bronze badges
5
the date format in mySQL have type (yyyy-mm-dd), now I try to reverse it (dd-mm-yyyy).
I got table user
CREATE TABLE USER
(
USER_ID INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY,
DOB DATE,
);
so when i insert value into that:
INSERT INTO USER(DOB) VALUES(DATE_FORMAT('13-07-1990','%d,%m,%Y));
however, it does not work. It notice that I should use 1990-07-13 instead of ’13-07-1990′.
please help me to do that. Thanks.
asked Nov 17, 2013 at 18:32
6
The ANSI SQL standard format for date is YYYY-MM-DD HH:MM:SS
. It’s easier to capture the date in this format for insertion into a database.
In order to store the date with the format you’re using (MM-DD-YYYY
) you need to use the STR_TO_DATE
function which allows you to convert a string to a date. The syntax for this function is:
STR_TO_DATE(str, format)
The specifiers for the format can be found here.
For your INSERT
statement, you would use:
INSERT INTO `user` (`dob`) VALUES
( STR_TO_DATE('13-07-1990','%d-%m-%Y') )
answered Nov 17, 2013 at 18:35
KermitKermit
33.5k13 gold badges83 silver badges120 bronze badges
4
DATE_FORMAT
is only used to save dates into varchar fields with non-standard formats or to retrieve them from the DB in a non-standard format. You may NOT save something in a DATE
type field as any format besides YYYY-MM-DD.
answered Nov 17, 2013 at 18:38
DevlshOneDevlshOne
8,3171 gold badge28 silver badges37 bronze badges
FROM THE DOCS : The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in ‘YYYY-MM-DD’ format. The supported range is ‘1000-01-01’ to ‘9999-12-31’.
My Way would be a little different.I would compute my date in php and pass the desired format to the query rather than computing it in query.
$your_date= "2010-03-21";
$desired_format = date("d-m-Y", strtotime($your_date));//returns 21-03-2010
$desired_format = date("m-d-Y", strtotime($your_date));//returns 03-21-2010
by using strtotime and date function,You can convert your date in to any format you desire
answered Nov 17, 2013 at 19:37
HIRA THAKURHIRA THAKUR
16.9k14 gold badges53 silver badges86 bronze badges
5
В этой статье мы рассмотрим основы работы с датой и временем в MySQL.
- Формат даты и времени
- Создание полей даты и времени
- Форматы даты и времени
- Функции даты и времени
- Внесение значений даты и времени в столбцы таблицы
- Извлечение данных по дате и времени
- Заключение
MySQL date format поддерживает несколько форматов даты и времени. Их можно определить следующим образом:
DATE — хранит значение даты в виде ГГГГ-ММ-ДД. Например, 2008-10-23.
DATETIME — хранит значение даты и времени в виде ГГГГ-MM-ДД ЧЧ:ММ:СС. Например, 2008-10-23 10:37:22. Поддерживаемый диапазон дат и времени: 1000-01-01 00:00:00 до 9999-12-31 23:59:59
TIMESTAMP — похож на DATETIME с некоторыми различиями в зависимости от версии MySQL и режима, в котором работает сервер.
Таблица, содержащая типы данных DATE и DATETIME, создается так же, как и другие столбцы. Например, мы можем создать новую таблицу под названием orders, которая содержит столбцы номера заказа, заказанного товара, даты заказа и даты доставки заказа:
CREATE TABLE `MySampleDB`.`orders` ( `order_no` INT NOT NULL AUTO_INCREMENT, `order_item` TEXT NOT NULL, `order_date` DATETIME NOT NULL, `order_delivery` DATE NOT NULL, PRIMARY KEY (`order_no`) ) ENGINE = InnoDB;
Столбец ORDER_DATE — это поле типа MySQL DATE TIME, в которое мы записываем дату и время, когда был сделан заказ. Для даты доставки невозможно предсказать точное время, поэтому мы записываем только дату.
Наиболее часто используемым разделителем для дат является тире (—), а для времени — двоеточие (:). Но мы можем использовать любой символ, или вообще не добавлять никакого символа.
Например, все следующие форматы являются правильными:
2008-10-23 10:37:22 20081023103722 2008/10/23 10.37.22 2008*10*23*10*37*22
MySQL содержит множество функций, которые используются для обработки даты и времени. В приведенной ниже таблице представлен список наиболее часто используемых функций:
Функция | Описание |
ADDDATE() | Добавляет дату. |
ADDTIME() | Добавляет время. |
CONVERT_TZ() | Конвертирует из одного часового пояса в другой. |
CURDATE() | Возвращает текущую дату. |
CURTIME() | Возвращает текущее системное время. |
DATE_ADD() | Добавляет одну дату к другой. |
DATE_FORMAT() | Задает указанный формат даты. |
DATE() | Извлекает часть даты из даты или выражения дата-время. |
DATEDIFF() | Вычитает одну дату из другой. |
DAYNAME() | Возвращает день недели. |
DAYOFMONTH() | Возвращает день месяца (1-31). |
DAYOFWEEK() | Возвращает индекс дня недели из аргумента. |
DAYOFYEAR() | Возвращает день года (1-366). |
EXTRACT() | Извлекает часть даты. |
FROM_DAYS() | Преобразует номер дня в дату. |
FROM_UNIXTIME() | Задает формат даты в формате UNIX. |
DATE_SUB() | Вычитает одну дату из другой. |
HOUR() | Извлекает час. |
LAST_DAY() | Возвращает последний день месяца для аргумента. |
MAKEDATE() | Создает дату из года и дня года. |
MAKETIME() | Возвращает значение времени. |
MICROSECOND() | Возвращает миллисекунды из аргумента. |
MINUTE() | Возвращает минуты из аргумента. |
MONTH() | Возвращает месяц из переданной даты. |
MONTHNAME() | Возвращает название месяца. |
NOW() | Возвращает текущую дату и время. |
PERIOD_ADD() | Добавляет интервал к месяцу-году. |
PERIOD_DIFF() | Возвращает количество месяцев между двумя периодами. |
QUARTER() | Возвращает четверть часа из переданной даты в качестве аргумента. |
SEC_TO_TIME() | Конвертирует секунды в формат ‘ЧЧ:MM:СС’. |
SECOND() | Возвращает секунду (0-59). |
STR_TO_DATE() | Преобразует строку в дату. |
SUBTIME() | Вычитает время. |
SYSDATE() | Возвращает время, в которое была выполнена функция. |
TIME_FORMAT() | Задает формат времени. |
TIME_TO_SEC() | Возвращает аргумент, преобразованный в секунды. |
TIME() | Выбирает часть времени из выражения, передаваемого в качестве аргумента. |
TIMEDIFF() | Вычитает время. |
TIMESTAMP() | С одним аргументом эта функция возвращает дату или выражение дата-время. С двумя аргументами возвращается сумма аргументов. |
TIMESTAMPADD() | Добавляет интервал к дате-времени. |
TIMESTAMPDIFF() | Вычитает интервал из даты — времени. |
TO_DAYS() | Возвращает аргумент даты, преобразованный в дни. |
UNIX_TIMESTAMP() | Извлекает дату-время в формате UNIX в формат, принимаемый MySQL. |
UTC_DATE() | Возвращает текущую дату по универсальному времени (UTC). |
UTC_TIME() | Возвращает текущее время по универсальному времени (UTC). |
UTC_TIMESTAMP() | Возвращает текущую дату-время по универсальному времени (UTC). |
WEEK() | Возвращает номер недели. |
WEEKDAY() | Возвращает индекс дня недели. |
WEEKOFYEAR() | Возвращает календарную неделю даты (1-53). |
YEAR() | Возвращает год. |
YEARWEEK() | Возвращает год и неделю. |
Вы можете поэкспериментировать с этими функциями MySQL date format, даже не занося никаких данных в таблицу. Например:
mysql> SELECT NOW(); +---------------------+ | NOW() | +---------------------+ | 2007-10-23 11:46:31 | +---------------------+ 1 row in set (0.00 sec)
Вы можете попробовать сочетание нескольких функций в одном запросе (например, чтобы найти день недели):
mysql> SELECT MONTHNAME(NOW()); +------------------+ | MONTHNAME(NOW()) | +------------------+ | October | +------------------+ 1 row in set (0.00 sec)
Рассмотрим, как вносятся значения date MySQL в таблицу. Чтобы продемонстрировать это, мы продолжим использовать таблицу orders, которую создали в начале статьи.
Мы начнем с добавления новой строки заказа. Значение поля order_no будет автоматически увеличиваться на 1, так что нам остается вставить значения order_item, дату создания заказа и дату доставки. Дата заказа — это время, в которое вставляется заказ, поэтому мы можем использовать функцию NOW(), чтобы внести в строку текущую дату и время.
Дата доставки — это период времени после даты заказа, которую мы можем вернуть, используя функцию MySQL DATE ADD(), которая принимает в качестве аргументов дату начала (в нашем случае NOW ()) и INTERVAL (в нашем случае 14 дней). Например:
INSERT INTO orders (order_item, order_date, order_delivery) VALUES ('iPhone 8Gb', NOW(), DATE_ADD(NOW(), INTERVAL 14 DAY));
Данный запрос создает заказ для указанного элемента с датой, временем выполнения заказа, и интервалом через две недели после этого в качестве даты доставки:
mysql> SELECT * FROM orders; +----------+------------+---------------------+----------------+ | order_no | order_item | order_date | order_delivery | +----------+------------+---------------------+----------------+ | 1 | iPhone 8Gb | 2007-10-23 11:37:55 | 2007-11-06 | +----------+------------+---------------------+----------------+ 1 row in set (0.00 sec)
Точно так же можно заказать товар с датой доставки через два месяца:
mysql> INSERT INTO orders (order_item, order_date, order_delivery) VALUES ('ipod Touch 4Gb', NOW(), DATE_ADD(NOW(), INTERVAL 2 MONTH)); Query OK, 1 row affected (0.00 sec) mysql> SELECT * FROM orders; +----------+----------------+---------------------+----------------+ | order_no | order_item | order_date | order_delivery | +----------+----------------+---------------------+----------------+ | 1 | iPhone 8Gb | 2007-10-23 11:37:55 | 2007-11-06 | | 2 | ipod Touch 4Gb | 2007-10-23 11:51:09 | 2007-12-23 | +----------+----------------+---------------------+----------------+ 2 rows in set (0.00 sec)
В MySQL мы можем отфильтровать извлеченные данные в зависимости от даты и времени. Например, мы можем извлечь только те заказы, доставка которых запланирована на ноябрь:
mysql> SELECT * FROM orders WHERE MONTHNAME(order_delivery) = 'November'; +----------+------------+---------------------+----------------+ | order_no | order_item | order_date | order_delivery | +----------+------------+---------------------+----------------+ | 1 | iPhone 8Gb | 2007-10-23 11:37:55 | 2007-11-06 | +----------+------------+---------------------+----------------+ 1 row in set (0.00 sec)
Точно так же мы можем использовать BETWEEN, чтобы выбрать товары, доставка которых произойдет между двумя указанными датами. Например:
mysql> SELECT * FROM orders WHERE order_delivery BETWEEN '2007-12-01' AND '2008-01-01'; +----------+----------------+---------------------+----------------+ | order_no | order_item | order_date | order_delivery | +----------+----------------+---------------------+----------------+ | 2 | ipod Touch 4Gb | 2007-10-23 11:51:09 | 2007-12-23 | +----------+----------------+---------------------+----------------+ 1 row in set (0.03 sec)
В этой статье мы рассмотрели форматы, используемые для определения даты и времени, и перечислили функции, используемые в для операций в MySQL с тип DATE. А также несколько примеров внесения и извлечения данных.
In this tutorial, we will learn about the MySQL DATE_FORMAT()
function. The date value in MySQL is in the format “YYYY-MM-DD”. However, such a date value may be difficult to read for some people – who prefer it in some other format like DD/MM/YYYY or MM/DD/YYYY. Some people may prefer to see the day name value as well. While sometimes, you may want to display the month name instead of month number in the date format. This is where the MySQL DATE_FORMAT()
function comes into play.
The MySQL DATE_FORMAT()
function formats a date value with a given specified format. You may also use MySQL DATE_FORMAT()
on datetime values and use some of the formats specified for the TIME_FORMAT()
function to format the time value as well. Let us take a look at the syntax of DATE_FORMAT()
and some examples.
Syntax of MySQL DATE_FORMAT()
Code language: SQL (Structured Query Language) (sql)
DATE_FORMAT(date, format)
Where ‘date’ is the date/datetime value that needs to be formatted and,
‘format’ is the format to be used. This value should be in quotes.
The ‘format’ can be one or a combination of the following –
- %a – Abbreviated weekday name (Sun to Sat)
- %b – Abbreviated month name (Jan to Dec)
- %c – Numeric month name (0 to 12)
- %D – Day of the month as a numeric value, followed by a suffix (1st, 2nd, 3rd, …)
- %d – Day of the month as a numeric value (01 to 31)
- %e – Day of the month as a numeric value (0 to 31)
- %f – Microseconds (000000 to 999999)
- %H – Hour (00 to 23)
- %h – Hour (00 to 12)
- %I – Hour (00 to 12)
- %i – Minutes (00 to 59)
- %j – Day of the year (001 to 366)
- %k – Hour (0 to 23)
- %l – Hour (1 to 12)
- %M – Month name in full (January to December)
- %m – Month name as a numeric value (00 to 12)
- %p – AM or PM
- %r – Time in 12 hour AM or PM format (hh:mm:ss AM/PM)
- %S – Seconds (00 to 59)
- %s – Seconds (00 to 59)
- %T – Time in 24 hour format (hh:mm:ss)
- %U – Week where Sunday is the first day of the week (00 to 53)
- %u – Week where Monday is the first day of the week (00 to 53)
- %V – Week where Sunday is the first day of the week (01 to 53). Used with %X
- %v – Week where Monday is the first day of the week (01 to 53). Used with %x
- %W – Weekday name in full (Sunday to Saturday)
- %w – Day of the week where Sunday=0 and Saturday=6
- %X – Year for the week where Sunday is the first day of the week. Used with %V
- %x – Year for the week where Monday is the first day of the week. Used with %v
- %Y – Year as a numeric, 4-digit value
- %y – Year as a numeric, 2-digit value
Examples of MySQL DATE_FORMAT()
Let us start with a basic example. Let us format the date value – ‘2021-01-15’. The first query should only display the year value from the date. This would be the equivalent of the YEAR()
function. The second query should display only the month value from the date. This would be the equivalent of the MONTH()
function. Let us write these queries using the SELECT
statement and aliases. The query is –
Code language: SQL (Structured Query Language) (sql)
SELECT DATE_FORMAT('2021-01-15', '%Y') AS Result; SELECT DATE_FORMAT('2021-01-15', '%m') AS Result;
And the output is –
Using Combination of Formats
For the date value – ‘2021-01-15′, let us display the date in the format “DD/MM/YY”. For this, we will need a combination of the format parameters. For the day values, we can use %d. To display the month value, we will use %m and for the two-digit year value, we will use %y. We will specify a / between %d, %m, and %y. The query is –
Code language: SQL (Structured Query Language) (sql)
SELECT DATE_FORMAT('2021-01-15', '%d/%m/%y') AS Result;
And the output is –
MySQL DATE_FORMAT() With NOW()
Let us use datetime values with MySQL DATE_FORMAT()
. Since NOW()
returns the current datetime value, we will use it in the query below. Let us format the result of the NOW() function to “DD/MM/YY HH:MM:SS AM/PM”. For the time formatting, we will use %r. The query is –
SELECT DATE_FORMAT(NOW(), '%d/%m/%y %r') AS Result;
Code language: SQL (Structured Query Language) (sql)
And the output is –
Displaying Day and Month Names
Let us write a query that displays the date in the format – ‘day_name, day_of_month month_name YYYY’. For displaying the day name, we will use %W. For displaying the day of the month, we will use %D. To display the full month name, we will use %M. The query is –
Code language: SQL (Structured Query Language) (sql)
SELECT DATE_FORMAT('2021-01-15', '%W, %D %M %Y') AS Result;
And the output is –
Lastly, let us display the date in a similar format as above, but this time, we will display short names for the day name and month name. We will also display the year as a two-digit value and the day of the month without the suffix. The query is –
Code language: SQL (Structured Query Language) (sql)
SELECT DATE_FORMAT('2021-01-15', '%a, %d %b %y') AS Result;
And the output is –
Working With Tables
Consider the below BusStop table.
Let us write a query that displays the bus details and the departure date formatted with the DATE_FORMAT()
function with the short names of day name and month name. The year value should be a four-digit value and the day of the name should be followed by a suffix. We should also display the departure time formatted as “HH:MM:SS AM/PM”. We will use the TIME_FORMAT()
function for the latter part. The query is –
SELECT Bus_No, Name, Start, End, DATE_FORMAT(DepartureTime, '%a, %D %b %Y') AS DepartureDate, TIME_FORMAT(DepartureTime, '%r') AS DepartureTime FROM BusStop;
Code language: SQL (Structured Query Language) (sql)
And the output is –
Conclusion
Formatting date and time values is a very important operation in MySQL and is widely used in a lot of use cases – especially when we have to make the date and time value presentable for the user. I would highly encourage you to practice a couple of examples of this function.
References
- MySQL Official documentation on the
DATE_FORMAT()
function.
Summary: in this tutorial, you will learn how to use the MySQL DATE_FORMAT function to format a date value based on a specific format.
Introduction to MySQL DATE_FORMAT
function
To format a date value to a specific format, you use the DATE_FORMAT
function. The syntax of the DATE_FORMAT
function is as follows:
Code language: SQL (Structured Query Language) (sql)
DATE_FORMAT(date,format)
The DATE_FORMAT
function accepts two arguments:
date
: is a valid date value that you want to formatformat
: is a format string that consists of predefined specifiers. Each specifier is preceded by a percentage character (%
). See the table below for a list of predefined specifiers.
The DATE_FORMAT
function returns a string whose character set and collation depend on the settings of the client’s connection.
The following table illustrates the specifiers and their meanings that you can use to construct a date format string:
Specifier | Meaning |
---|---|
%a | Three-characters abbreviated weekday name e.g., Mon, Tue, Wed, etc. |
%b | Three-characters abbreviated month name e.g., Jan, Feb, Mar, etc. |
%c | Month in numeric e.g., 1, 2, 3…12 |
%D | Day of the month with English suffix e.g., 0th, 1st, 2nd, etc. |
%d | Day of the month with leading zero if it is 1 number e.g., 00, 01,02, …31 |
%e | Day of the month without leading zero e.g., 1,2,…31 |
%f | Microseconds in the range of 000000..999999 |
%H | Hour in 24-hour format with leading zero e.g., 00..23 |
%h | Hour in 12-hour format with leading zero e.g., 01, 02…12 |
%I | Same as %h |
%i | Minutes with leading zero e.g., 00, 01,…59 |
%j | Day of year with leading zero e.g., 001,002,…366 |
%k | Hour in 24-hour format without leading zero e.g., 0,1,2…23 |
%l | Hour in 12-hour format without leading zero e.g., 1,2…12 |
%M | Full month name e.g., January, February,…December |
%m | Month name with leading zero e.g., 00,01,02,…12 |
%p | AM or PM, depending on other time specifiers |
%r | Time in 12-hour format hh:mm:ss AM or PM |
%S | Seconds with leading zero 00,01,…59 |
%s | Same as %S |
%T | Time in 24-hour format hh:mm:ss |
%U | Week number with leading zero when the first day of week is Sunday e.g., 00,01,02…53 |
%u | Week number with leading zero when the first day of week is Monday e.g., 00,01,02…53 |
%V | Same as %U; it is used with %X |
%v | Same as %u; it is used with %x |
%W | Full name of weekday e.g., Sunday, Monday,…, Saturday |
%w | Weekday in number (0=Sunday, 1= Monday,etc.) |
%X | Year for the week in four digits where the first day of the week is Sunday; often used with %V |
%x | Year for the week, where the first day of the week is Monday, four digits; used with %v |
%Y | Four digits year e.g., 2000 and 2001. |
%y | Two digits year e.g., 10,11,and 12. |
%% | Add percentage (%) character to the output |
The following are some commonly used date format strings:
DATE_FORMAT string | Formatted date |
---|---|
%Y-%m-%d | 2013-07-04 |
%e/%c/%Y | 4/7/2013 |
%c/%e/%Y | 7/4/2013 |
%d/%m/%Y | 4/7/2013 |
%m/%d/%Y | 7/4/2013 |
%e/%c/%Y %H:%i | 4/7/2013 11:20 |
%c/%e/%Y %H:%i | 7/4/2013 11:20 |
%d/%m/%Y %H:%i | 4/7/2013 11:20 |
%m/%d/%Y %H:%i | 7/4/2013 11:20 |
%e/%c/%Y %T | 4/7/2013 11:20 |
%c/%e/%Y %T | 7/4/2013 11:20 |
%d/%m/%Y %T | 4/7/2013 11:20 |
%m/%d/%Y %T | 7/4/2013 11:20 |
%a %D %b %Y | Thu 4th Jul 2013 |
%a %D %b %Y %H:%i | Thu 4th Jul 2013 11:20 |
%a %D %b %Y %T | Thu 4th Jul 2013 11:20:05 |
%a %b %e %Y | Thu Jul 4 2013 |
%a %b %e %Y %H:%i | Thu Jul 4 2013 11:20 |
%a %b %e %Y %T | Thu Jul 4 2013 11:20:05 |
%W %D %M %Y | Thursday 4th July 2013 |
%W %D %M %Y %H:%i | Thursday 4th July 2013 11:20 |
%W %D %M %Y %T | Thursday 4th July 2013 11:20:05 |
%l:%i %p %b %e, %Y | 7/4/2013 11:20 |
%M %e, %Y | 4-Jul-13 |
%a, %d %b %Y %T | Thu, 04 Jul 2013 11:20:05 |
MySQL DATE_FORMAT
examples
Let’s take a look at the orders
table in the sample database.
To select the order’s data and format the date value, you use the following statement:
Code language: SQL (Structured Query Language) (sql)
SELECT orderNumber, DATE_FORMAT(orderdate, '%Y-%m-%d') orderDate, DATE_FORMAT(requireddate, '%a %D %b %Y') requireddate, DATE_FORMAT(shippedDate, '%W %D %M %Y') shippedDate FROM orders;
Try It Out
We formatted the order date, required date, and shipped date of each order based on different date formats specified by the format strings.
MySQL DATE_FORMAT
with ORDER BY
See the following example:
Code language: SQL (Structured Query Language) (sql)
SELECT orderNumber, DATE_FORMAT(shippeddate, '%W %D %M %Y') shippeddate FROM orders WHERE shippeddate IS NOT NULL ORDER BY shippeddate;
Try It Out
In the query, we selected all orders whose shipped date are not NULL
and sorted the orders by the shipped date. However, the orders were not sorted correctly.
The reason is that we used shippeddate
as the alias for the output of the DATE_FORMAT
function, which is a string, the ORDER BY clause took the alias and sorted the orders based on string values, not date values.
To fix this problem, we have to use an alias that is different from the column name; see the following statement:
Code language: SQL (Structured Query Language) (sql)
SELECT orderNumber, DATE_FORMAT(shippeddate, '%W %D %M %Y') 'Shipped date' FROM orders WHERE shippeddate IS NOT NULL ORDER BY shippeddate;
Try It Out
In this tutorial, we have shown you how to use the MySQL DATE_FORMAT
function to format the date based on a specified format.
Was this tutorial helpful?
Функция DATE_FORMAT преобразует дату из формата год-месяц-день
или формата год-месяц-день часы:минуты:секунды в другой удобный нам формат.
К примеру, из год-месяц-день можно сделать день.месяц.год
или месяц—год
См. также функцию TIME_FORMAT,
которая меняет формат вывода времени.
Синтаксис
SELECT DATE_FORMAT(дата, формат) FROM имя_таблицы WHERE условие
Команды
Можно использовать следующие команды,
чтобы сделать нужный формат вывода:
Команда | Описание |
---|---|
%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 |
Пример
В данном примере при выборке создается новое поле,
в котором будет лежать дата в другом формате:
SELECT *, DATE_FORMAT(date, '%d.%m.%Y') as new_date FROM workers
SQL запрос выберет следующие строки:
id айди |
name имя |
date дата регистрации |
new_date дата в новом формате |
---|---|---|---|
1 | Дима | 2010-03-01 12:01:02 | 01.03.2010 |
2 | Петя | 2011-04-02 13:02:03 | 02.04.2011 |
3 | Вася | 2012-05-03 14:03:04 | 03.05.2012 |