Replace date format with MySQL STR_TO_DATE


Let us first create a table −

mysql> create table DemoTable(DueDate varchar(100));
Query OK, 0 rows affected (0.78 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('10-01-2019 10:19:20');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('12-03-2018 11:00:00');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('02-23-2018 04:20:40');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+---------------------+
| DueDate             |
+---------------------+
| 10-01-2019 10:19:20 |
| 12-03-2018 11:00:00 |
| 02-23-2018 04:20:40 |
+---------------------+
3 rows in set (0.00 sec)

Following is the query to replace date format with MySQL STR_TO_DATE −

mysql> SELECT STR_TO_DATE(REPLACE(DueDate,"'",''), '%c-%e-%Y %T') from DemoTable;

This will produce the following output −

+-----------------------------------------------------+
| STR_TO_DATE(REPLACE(DueDate,"'",''), '%c-%e-%Y %T') |
+-----------------------------------------------------+
| 2019-10-01 10:19:20                                 |
| 2018-12-03 11:00:00                                 |
| 2018-02-23 04:20:40                                 |
+-----------------------------------------------------+
3 rows in set (0.00 sec)

Updated on: 22-Aug-2019

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements