In MySQL, convert datetime to integer using UNIX_TIMESTAMP() function. The syntax is as follows:
SELECT UNIX_TIMESTAMP(yourDatetimeColumnName) as anyVariableName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table DatetimeToInteger -> ( -> Id int NOT NULL AUTO_INCREMENT, -> ArrivalTime datetime, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.94 sec)
Insert some records in the table using insert command. The query is as follows:
mysql> insert into DatetimeToInteger(ArrivalTime) values(now()); Query OK, 1 row affected (0.09 sec) mysql> insert into DatetimeToInteger(ArrivalTime) values(curdate()); Query OK, 1 row affected (0.21 sec) mysql> insert into DatetimeToInteger(ArrivalTime) values('2017-09-21 13:10:55'); Query OK, 1 row affected (0.25 sec) mysql> insert into DatetimeToInteger(ArrivalTime) values(date_add(now(),interval 3 year)); Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from DatetimeToInteger;
The following is the output:
+----+---------------------+ | Id | ArrivalTime | +----+---------------------+ | 1 | 2019-01-22 15:12:45 | | 2 | 2019-01-22 00:00:00 | | 3 | 2017-09-21 13:10:55 | | 4 | 2022-01-22 15:14:32 | +----+---------------------+ 4 rows in set (0.00 sec)
Here is the query to convert datetime to integer:
mysql> select unix_timestamp(ArrivalTime) as DateTimeToIntegerDemo from DatetimeToInteger;
The following is the output:
+-----------------------+ | DateTimeToIntegerDemo | +-----------------------+ | 1548150165 | | 1548095400 | | 1505979655 | | 1642844672 | +-----------------------+ 4 rows in set (0.00 sec)