Converting date from 'dd/mm/yyyy' to 'yyyymmdd' in MySQL

MySQLMySQLi Database

To convert date from 'dd/mm/yyyy' to 'yyyymmdd', you can use the date_format() method. Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Admissiondate varchar(200)
);
Query OK, 0 rows affected (0.54 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Admissiondate) values('21/10/2014');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(Admissiondate) values('01/12/2016');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Admissiondate) values('31/01/2017');
Query OK, 1 row affected (0.14 sec)

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

mysql> select *from DemoTable;

This will produce the following output −

+----+---------------+
| Id | Admissiondate |
+----+---------------+
| 1  | 21/10/2014    |
| 2  | 01/12/2016    |
| 3  | 31/01/2017    |
+----+---------------+
3 rows in set (0.00 sec)

Following is the query to convert date from 'dd/mm/yyyy' to 'yyyymmdd' −

mysql> select date_format(str_to_date(Admissiondate,'%d/%m/%Y'),'%Y%m%d') from DemoTable;

This will produce the following output −

+-------------------------------------------------------------+
| date_format(str_to_date(Admissiondate,'%d/%m/%Y'),'%Y%m%d') |
+-------------------------------------------------------------+
| 20141021                                                    |
| 20161201                                                    |
| 20170131                                                    |
+-------------------------------------------------------------+
3 rows in set (0.00 sec)
raja
Published on 29-Apr-2019 15:11:37
Advertisements