ใน MySQL ใช้ TIME_TO_SEC() ใน PHP ใช้ strtotime() เพื่อแปลง datetime เป็น Unix timestamp (วินาที)
MySQL Syntax
SELECT TIME_TO_SEC(ABS(TIMEDIFF('yourDateTimeValue', NOW())));
PHP Implementation
ติดตั้ง XAMPP Server แล้วสร้างไฟล์ PHP ใน C:\xampp\htdocs\phpproject\
ไฟล์ DifferenceInSeconds.php
<?php $MySQLDateTime = '2019-01-29 13:50:40'; echo "<h1>The strtotime value is:</h1>" . strtotime($MySQLDateTime) . "<br>"; echo "<h1>The time value is:</h1>" . time() . "<br>"; $diffenceInSeconds = strtotime($MySQLDateTime) - time(); echo "<h1>The difference of both time in seconds is:</h1>" . $diffenceInSeconds; ?>
เข้าถึงผ่านเบราว์เซอร์: https://localhost:8086/phpproject/DifferenceInSeconds.php (พอร์ตอาจแตกต่างไป)
ผลลัพธ์จะแสดง: - ค่า strtotime ของ datetime ที่กำหนด - ค่า time() ปัจจุบัน (Unix timestamp) - ความต่างเป็นวินาที
หมายเหตุ: strtotime() คืนค่า Unix timestamp (วินาทีจาก 1 Jan 1970) เทียบเท่ากับ TIME_TO_SEC ในบริบทบางอย่าง แต่ TIME_TO_SEC แปลงค่า TIME (ชั่วโมง:นาที:วินาที) เป็นวินาที ส่วน strtotime แปลง datetime ทั้งหมด