How to select only MySQL date from datetime column?

MySQLMySQLi Database

Use DATE_FORMAT for this. Let us first create a table −

mysql> create table DemoTable
   (
   ShippingDate varchar(200)
    );
Query OK, 0 rows affected (0.25 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('04:58 PM 10/31/2018');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable values('02:30 AM 01/01/2019');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable values('12:01 AM 05/03/2019');
Query OK, 1 row affected (0.06 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+---------------------+
| ShippingDate        |
+---------------------+
| 04:58 PM 10/31/2018 |
| 02:30 AM 01/01/2019 |
| 12:01 AM 05/03/2019 |
+---------------------+
3 rows in set (0.00 sec)

Following is the query to select only date from datetime column −

mysql> SELECT DATE_FORMAT(STR_TO_DATE(ShippingDate, '%h:%i %p %m/%d/%Y'), '%m/%d/%Y') from DemoTable;

This will produce the following output displaying only date −

+-------------------------------------------------------------------------+
| DATE_FORMAT(STR_TO_DATE(ShippingDate, '%h:%i %p %m/%d/%Y'), '%m/%d/%Y') |
+-------------------------------------------------------------------------+
| 10/31/2018                                                              |
| 01/01/2019                                                              |
| 05/03/2019                                                              |
+-------------------------------------------------------------------------+
3 rows in set (0.00 sec)
raja
Published on 20-May-2019 12:15:53
Advertisements