Convert INT to DATETIME in MySQL?


You can use the in-built function from_unixtime() to convert INT to DATETIME. The syntax is as follows −

SELECT FROM_UNIXTIME(yourColumnName,’%Y-%m-%d') as AnyVariableName from
yourTableName;

To understand the above syntax, let us first create a table. The query to create a table is as follows −

mysql> create table IntToDateDemo
   -> (
   -> Number int
   -> );
Query OK, 0 rows affected (0.59 sec)

Insert some records in the table using insert command. The query to insert record is as follows −

mysql> truncate table IntToDateDemo;
Query OK, 0 rows affected (4.11 sec)

mysql> insert into IntToDateDemo values(1545284721);
Query OK, 1 row affected (0.19 sec)

mysql> insert into IntToDateDemo values(1576820738);
Query OK, 1 row affected (0.19 sec)

mysql> insert into IntToDateDemo values(1513748752);
Query OK, 1 row affected (0.24 sec)

mysql> insert into IntToDateDemo values(1671515204);
Query OK, 1 row affected (0.18 sec)

Now you can display all records from the table using select statement. The query is as follows −

mysql> select *from IntToDateDemo;

Output

+------------+
| Number     |
+------------+
| 1545284721 |
| 1576820738 |
| 1513748752 |
| 1671515204 |
+------------+
4 rows in set (0.00 sec)

Here is the query that converts int to datetime using from_unixtime() function. The query is as follows −

mysql> select from_unixtime(Number,'%Y-%m-%d') as DateDemo from IntToDateDemo;

The following is the output displaying the converted datetime −

+------------+
| DateDemo   |
+------------+
| 2018-12-20 |
| 2019-12-20 |
| 2017-12-20 |
| 2022-12-20 |
+------------+
4 rows in set (0.00 sec)

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements