Convert VARCHAR data to MySQL date format?

MySQLMySQLi Database

To convert VARCHAR data to date format, you can use STR_TO_DATE() −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable1989 values('31/01/2015');
Query OK, 1 row affected (0.52 sec)
mysql> insert into DemoTable1989 values('01/12/2018');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1989 values('25/10/2019');
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1989;

This will produce the following output −

+------------+
| DueDate    |
+------------+
| 31/01/2015 |
| 01/12/2018 |
| 25/10/2019 |
+------------+
3 rows in set (0.00 sec)

Here is the query to convert date data into MySQL date format:

mysql> select str_to_date(DueDate,'%d/%m/%Y') as MySQLDateFormat from DemoTable1989;

This will produce the following output −

+-----------------+
| MySQLDateFormat |
+-----------------+
| 2015-01-31      |
| 2018-12-01      |
| 2019-10-25      |
+-----------------+
3 rows in set (0.05 sec)
raja
Published on 02-Jan-2020 09:46:58
Advertisements