How to correctly convert a date format into a MySQL date?


Use the STR_TO_DATE() method for this. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> DueDatetime varchar(100)
   -> );
Query OK, 0 rows affected (1.03 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('22-06-2019 14:40');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values('02-07-2015 13:10');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------------------+
| DueDatetime      |
+------------------+
| 22-06-2019 14:40 |
| 02-07-2015 13:10 |
+------------------+
2 rows in set (0.00 sec)

Following is the query for conversion −

mysql> select str_to_date(DueDatetime,'%d-%m-%Y %H:%i') from DemoTable;

This will produce the following output −

+-------------------------------------------+
| str_to_date(DueDatetime,'%d-%m-%Y %H:%i') |
+-------------------------------------------+
| 2019-06-22 14:40:00                       |
| 2015-07-02 13:10:00                       |
+-------------------------------------------+
2 rows in set (0.00 sec)
raja
Published on 11-Jul-2019 11:39:14
Advertisements