Languages
[Edit]
EN

MySQL - date to string (dd/mm/yyyy)

0 points
Created by:
Mohammad-Oneal
327

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 from 01 to 12),
  • DD - day number (from 01 to 31 - 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 to 31),
  • %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:

MySQL - convert date to string - result
MySQL - convert date to string - result

Example 2 - Convert dates in column

To show how to convert date to a string, we will use the following table:

MySQL - example data used to convert date to string
MySQL - example data used to convert date to string

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:

MySQL - format date column to string - result
MySQL - format date column to string - 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');

Related posts

Alternative titles

  1. MySQL - date format to varchar
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

MySQL - dates

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join