How to cast DATETIME as a DATE in MySQL?


To cast DATETIME as a DATE in MySQL, use the CAST() function. The syntax is as follows −

select cast(yourColumnName as Date) as anyVariableName from yourTableName;

To understand the above syntax, let us first create a table −

mysql> create table ConvertDatetimeToDate
−> (
   −> YourDatetime datetime
−> );
Query OK, 0 rows affected (0.95 sec)

Inserting datetime into the table with the help of insert command. The query is as follows −

mysql> insert into ConvertDatetimeToDate values(date_add(now(),interval 1 day));
Query OK, 1 row affected (0.17 sec)

mysql> insert into ConvertDatetimeToDate values(date_add(now(),interval -1 day));
Query OK, 1 row affected (0.15 sec)

mysql> insert into ConvertDatetimeToDate values(date_add(now(),interval 1 year));
Query OK, 1 row affected (0.10 sec)

mysql> insert into ConvertDatetimeToDate values(date_add(now(),interval -1 year));
Query OK, 1 row affected (0.16 sec)

Display all the records inserted above. The query is as follows −

mysql> select *from ConvertDatetimeToDate;

The following is the output −

+---------------------+
|       YourDatetime  |
+---------------------+
| 2018-11-28 16:12:50 |
| 2018-11-26 16:13:00 |
| 2019-11-27 16:13:13 |
| 2017-11-27 16:13:24 |
+---------------------+
4 rows in set (0.00 sec)

Now you can apply the above syntax to cast datetime to date. The query is as follows −

mysql> select cast(YourDatetime as Date) as OnlyDateDemo from ConvertDatetimeToDate;

The following is the output −

+--------------+
| OnlyDateDemo |
+--------------+
| 2018-11-28   |
| 2018-11-26   |
| 2019-11-27   |
| 2017-11-27   |
+--------------+
4 rows in set (0.00 sec)

Updated on: 29-Jun-2020

386 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements