How to convert a date format in MySQL?

MySQLMySQLi Database

To convert a date format, use STR_TO_DATE() −

mysql> create table DemoTable2010
(
   DueDate varchar(20)
);
Query OK, 0 rows affected (0.68 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2010 values('12/10/2019 12:34:00');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable2010 values('12/12/2011 11:00:20');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable2010 values('31/01/2017 11:00:20');
Query OK, 1 row affected (0.23 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable2010;

This will produce the following output −

+---------------------+
| DueDate             |
+---------------------+
| 12/10/2019 12:34:00 |
| 12/12/2011 11:00:20 |
| 31/01/2017 11:00:20 |
+---------------------+
3 rows in set (0.00 sec)

Here is the query to convert date format −

mysql> select str_to_date(DueDate,'%d/%m/%Y %k:%i') from DemoTable2010;

This will produce the following output −

+---------------------------------------+
| str_to_date(DueDate,'%d/%m/%Y %k:%i') |
+---------------------------------------+
| 2019-10-12 12:34:00                   |
| 2011-12-12 11:00:00                   |
| 2017-01-31 11:00:00                   |
+---------------------------------------+
3 rows in set, 3 warnings (0.00 sec)
raja
Published on 02-Jan-2020 10:36:39
Advertisements