Convert Date not in a proper format with MySQL?



Assume that the date is in varchar data type i.e. not in the date format.

Let us first create a table. Following is the query −

mysql> create table convertDateDemo    -> (    -> AdmissionDate varchar(200)    -> ); Query OK, 0 rows affected (0.63 sec)

Following is the query to insert some records in the table using insert command −

mysql> insert into convertDateDemo values('April 04 2019'); Query OK, 1 row affected (0.18 sec) mysql> insert into convertDateDemo values('May 05 2018'); Query OK, 1 row affected (0.16 sec) mysql> insert into convertDateDemo values('January 01 2012'); Query OK, 1 row affected (0.12 sec) mysql> insert into convertDateDemo values('June 12 2016'); Query OK, 1 row affected (0.16 sec)

Following is the query to display all records from the table using select statement −

mysql> select * from convertDateDemo;

This will produce the following output −

+-----------------+ | AdmissionDate | +-----------------+ | April 04 2019 | | May 05 2018 | | January 01 2012 | | June 12 2016 | +-----------------+ 4 rows in set (0.00 sec)

Here is the query to convert date with MySQL −

mysql> select STR_TO_DATE(AdmissionDate, '%M %e %Y %l:%i%p') AS ConvertDate from convertDateDemo;

This will produce the following output −

+---------------------+ | ConvertDate | +---------------------+ | 2019-04-04 00:00:00 | | 2018-05-05 00:00:00 | | 2012-01-01 00:00:00 | | 2016-06-12 00:00:00 | +---------------------+ 4 rows in set (0.05 sec)
Updated on: 2019-07-30T22:30:25+05:30

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements