How to convert char field to datetime field in MySQL?

MySQLMySQLi Database

Let us first create a table. Here, we have declared dates in char type −

mysql> create table DemoTable1472
   -> (
   -> ShippingDate char(35)
   -> );
Query OK, 0 rows affected (0.46 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1472 values('12/31/2017 10:50');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1472 values('01/10/2018 12:00');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1472 values('03/20/2019 09:30');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1472;

This will produce the following output −

+------------------+
| ShippingDate     |
+------------------+
| 12/31/2017 10:50 |
| 01/10/2018 12:00 |
| 03/20/2019 09:30 |
+------------------+
3 rows in set (0.00 sec)

Following is the query to convert char field to datetime field in MySQL −

mysql> select str_to_date(replace(ShippingDate,'/',','),'%,%,% %T') from DemoTable1472;

This will produce the following output −

+----------------------------------------------------------+
| str_to_date(replace(ShippingDate,'/',','),'%m,%d,%Y %T') |
+----------------------------------------------------------+
| 2017-12-31 10:50:00                                      |
| 2018-01-10 12:00:00                                      |
| 2019-03-20 09:30:00                                      |
+----------------------------------------------------------+
3 rows in set (0.00 sec)
raja
Published on 10-Dec-2019 07:40:30
Advertisements