Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

MySQL: แปลง Datetime เป็น Integer ด้วย UNIX_TIMESTAMP()


ใน MySQL แปลง Datetime เป็น Integer ใช้ฟังก์ชัน UNIX_TIMESTAMP()

Syntax

SELECT UNIX_TIMESTAMP(yourDatetimeColumnName) AS anyVariableName FROM yourTableName;

ตัวอย่าง

mysql> CREATE TABLE DatetimeToInteger (
    -> Id INT NOT NULL AUTO_INCREMENT,
    -> ArrivalTime DATETIME,
    -> PRIMARY KEY(Id)
    -> );
mysql> INSERT INTO DatetimeToInteger(ArrivalTime) VALUES
    -> (NOW()), (CURDATE()), ('2017-09-21 13:10:55'), (DATE_ADD(NOW(), INTERVAL 3 YEAR));

ข้อมูลในตาราง

+----+---------------------+
| 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 |
+----+---------------------+

Query แปลง

mysql> SELECT UNIX_TIMESTAMP(ArrivalTime) AS DateTimeToIntegerDemo FROM DatetimeToInteger;

ผลลัพธ์

+-----------------------+
| DateTimeToIntegerDemo |
+-----------------------+
| 1548150165            |
| 1548095400            |
| 1505979655            |
| 1642844672            |
+-----------------------+