Convert VARCHAR Date to a different format in MySQL?



Let’s say you have set dates in the VARCHAR format. Now if you want to update the format, then use the UPDATE command along with STR_TO_DATE(). The syntax is as follows −

update yourTableName set yourColumnName=str_to_date(yourColumnName,'%m/%d/%Y');

Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values('12/01/2019');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('01/31/2016');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('03/17/2018');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('07/25/2017');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------------+
| DueDate    |
+------------+
| 12/01/2019 |
| 01/31/2016 |
| 03/17/2018 |
| 07/25/2017 |
+------------+
4 rows in set (0.00 sec)

Following is the query to convert varchar data to a different format in MySQL −

mysql> update DemoTable set DueDate=str_to_date(DueDate,'%m/%d/%Y');
Query OK, 4 rows affected (0.18 sec)
Rows matched: 4 Changed: 4 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+------------+
| DueDate    |
+------------+
| 2019-12-01 |
| 2016-01-31 |
| 2018-03-17 |
| 2017-07-25 |
+------------+
4 rows in set (0.00 sec)

Advertisements