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

MySQL: แปลง DateTime เป็นตัวเลข (Unix Timestamp) ด้วย UNIX_TIMESTAMP()


แปลง DateTime เป็นตัวเลข (Unix Timestamp) ใช้ UNIX_TIMESTAMP()

Syntax

SELECT UNIX_TIMESTAMP(yourColumnName) AS anyVariableName FROM yourTableName;

ตัวอย่าง

mysql> CREATE TABLE DateTimeToNumberDemo (
    -> Id INT NOT NULL AUTO_INCREMENT,
    -> releasedDate DATETIME,
    -> PRIMARY KEY(Id)
    -> );
mysql> INSERT INTO DateTimeToNumberDemo(releasedDate) VALUES
    -> (NOW()), (CURDATE()), ('1978-01-19'), ('2016-09-13'), ('2017-11-12'), ('2018-12-09');

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

+----+---------------------+
| Id | releasedDate        |
+----+---------------------+
| 1  | 2019-01-12 21:20:57 |
| 2  | 2019-01-12 00:00:00 |
| 3  | 1978-01-19 00:00:00 |
| 4  | 2016-09-13 00:00:00 |
| 5  | 2017-11-12 00:00:00 |
| 6  | 2018-12-09 00:00:00 |
+----+---------------------+

Query แปลงเป็นตัวเลข

mysql> SELECT UNIX_TIMESTAMP(releasedDate) AS DateToNumber FROM DateTimeToNumberDemo;

ผลลัพธ์ (Unix Timestamp)

+--------------+
| DateToNumber |
+--------------+
| 1547308257   |
| 1547231400   |
| 253996200    |
| 1473705000   |
| 1510425000   |
| 1544293800   |
+--------------+