How to convert date YYYYMMDD to YY-MM-DD in MySQL query?


To convert date YYYYMMDD to YY-MM-DD in MySQL, use the below syntax −

select date_format(str_to_date(yourColumnName, '%Y%m%d'),'%Y-%m-%d') from yourTableName;

Let us first create a table −

mysql> create table DemoTable
(
   ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ClientProjectDeadline varchar(200)
);
Query OK, 0 rows affected (0.57 sec)

Insert some records in the table using insert command. We have inserted dates in the YYYYMMDD format −

mysql> insert into DemoTable(ClientProjectDeadline) values('20121221');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(ClientProjectDeadline) values('20190416');
Query OK, 1 row affected (0.53 sec)
mysql> insert into DemoTable(ClientProjectDeadline) values('20160624');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(ClientProjectDeadline) values('20170131');
Query OK, 1 row affected (0.20 sec)

Following is the query to display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----------+-----------------------+
| ClientId | ClientProjectDeadline |
+----------+-----------------------+
| 1        | 20121221              |
| 2        | 20190416              |
| 3        | 20160624              |
| 4        | 20170131              |
+----------+-----------------------+
4 rows in set (0.00 sec)

Following is the query to convert date YYYYMMDD to YY-MM-DD in MySQL −

mysql> select date_format(str_to_date(ClientProjectDeadline, '%Y%m%d'),'%Y-%m-%d') from DemoTable;

This will produce the following output −

+----------------------------------------------------------------------+
| date_format(str_to_date(ClientProjectDeadline, '%Y%m%d'),'%Y-%m-%d') |
+----------------------------------------------------------------------+
| 2012-12-21                                                           |
| 2019-04-16                                                           |
| 2016-06-24                                                           |
| 2017-01-31                                                           |
+----------------------------------------------------------------------+
4 rows in set (0.05 sec)

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements