Format date with DATE_FORMAT() and STR_TO_DATE() in MySQL


Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values('August 04,2019');
Query OK, 1 row affected (0.25 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----------------+
| DueDate        |
+----------------+
| August 04,2019 |
+----------------+
1 row in set (0.00 sec)

Following is the query to format date −

mysql> set @stringToDate=(select date_format(str_to_date(DueDate, '%M %d,%Y'), '%Y-%m-%d') from DemoTable);
Query OK, 0 rows affected (0.02 sec)

Let us use a select statement to display the date −

mysql> select @stringToDate;

This will produce the following output −

+---------------+
| @stringToDate |
+---------------+
| 2019-08-04    |
+---------------+
1 row in set (0.00 sec)

Updated on: 04-Oct-2019

203 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements