EN
MySQL - date to string (dd/mm/yyyy)
0
points
In this article, we would like to show you how to convert date to string in MySQL.
Quick solution
1. Convert one date only:
SELECT DATE_FORMAT('YYYY-MM-DD', "%e %M %Y") AS 'alias_name';
Where:
YYYY
- 4-digit year format, e.g.2021
,MM
- month number (counted from01
to12
),DD
- day number (from01
to31
- depending on the month),
2. Convert whole column:
SELECT DATE_FORMAT(`date_column_name`, "%e %M %Y") AS 'alias_name'
FROM `table_name`;
Where
%e
- day of the month as a numeric value (0
to31
),%M
- full month name,%Y
- year as a numeric, 4-digit value.
Note:
Go to the official documentation to find more date format specifiers such as
%e
,%M
and%Y
.
Practical examples
Example 1 - Convert one date
In this example, we will convert example date to the day-month-year format.
Query:
SELECT DATE_FORMAT('2021-02-01', "%e %M %Y") AS 'formatted_date';
Result:
Example 2 - Convert dates in column
To show how to convert date to a string, we will use the following table:
Note:
At the end of this article you can find database preparation SQL queries.
In this example, we will display the registration_time
column as string in the day-month-year format.
Query:
SELECT
`id`, `username`,
DATE_FORMAT(`registration_time`, "%e %M %Y") AS 'registration_date'
FROM `users`;
Result:
Database preparation
create_tables.sql
file:
CREATE TABLE `users` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`username` VARCHAR(50) NOT NULL,
`registration_time` DATETIME NOT NULL,
PRIMARY KEY (`id`)
);
insert_data.sql
file:
INSERT INTO `users`
(`username`, `registration_time`)
VALUES
('Tom', '2021-01-01 11:41:31'),
('Chris','2021-01-02 11:42:45'),
('Jack','2021-01-03 15:13:39'),
('Kim','2021-01-03 15:24:51'),
('Marco','2021-01-04 22:35:38'),
('Kate','2021-01-04 22:46:51'),
('Nam','2021-01-04 22:57:37');