การเตรียมข้อมูล
mysql> CREATE TABLE DemoTable1894 (
Id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
DueTime INT
);
mysql> INSERT INTO DemoTable1894 VALUES(), (), ();
อัปเดต DueTime ด้วย UNIX_TIMESTAMP(NOW())
mysql> UPDATE DemoTable1894 SET DueTime = UNIX_TIMESTAMP(NOW());
Query OK, 3 rows affected
ผลลัพธ์
mysql> SELECT * FROM DemoTable1894;
+----+------------+
| Id | DueTime |
+----+------------+
| 1 | 1576042722 |
| 2 | 1576042722 |
| 3 | 1576042722 |
+----+------------+
UNIX_TIMESTAMP()
| การใช้งาน | คืนค่า |
| UNIX_TIMESTAMP() | Current Timestamp (Seconds since 1970-01-01 UTC) |
| UNIX_TIMESTAMP(date) | Timestamp ของ Date/DateTime ที่ระบุ |
| FROM_UNIXTIME(ts) | แปลง Timestamp → DateTime |
| FROM_UNIXTIME(ts, format) | แปลงพร้อม Format |
คอลัมน์ Type สำหรับ Timestamp
| Type | Range | Storage | Timezone |
| INT / BIGINT | 1970-2038 / ยาวกว่า | 4/8 bytes | ไม่มี (App จัดการ) |
| TIMESTAMP | 1970-2038 | 4 bytes | Auto UTC ↔ Session TZ |
| DATETIME | 1000-9999 | 5/8 bytes | ไม่มี |
Best Practice: ใช้ TIMESTAMP Column
CREATE TABLE events (
id INT PRIMARY KEY,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
-- Auto-set ตอน Insert และ Update
Application Layer (แนะนำ)
-- Java
ps.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
-- Python
cursor.execute("INSERT INTO t(ts) VALUES (%s)", (datetime.utcnow(),))
-- PHP
$pdo->prepare("INSERT INTO t(ts) VALUES (?)")->execute([time()]);
ข้อควรระวัง
- Y2038 Problem: 32-bit INT overflow ในปี 2038 → ใช้ BIGINT หรือ TIMESTAMP (64-bit ใน MySQL 8.0+)
- Timezone: UNIX_TIMESTAMP() คืนค่า UTC, NOW() คืนค่า Session Timezone
- Consistency: ใช้ UTC ทุกที่ แปลงตอนแสดงผลเท่านั้น