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

จัดการเวลาใน PHP และ MySQL: แปลงรูปแบบ 12/24 ชั่วโมง


PHP: แปลง 12 ชั่วโมงเป็น 24 ชั่วโมง

ใช้ strtotime() ร่วมกับ date()

โค้ด PHP

$timeValue = '8:55 PM';
$changeTimeFormat = date('H:i:s', strtotime($timeValue));
echo "The change Format in 24 Hours = " . $changeTimeFormat;

ผลลัพธ์

The change Format in 24 Hours = 20:55:00

MySQL: แปลง 24 ชั่วโมงเป็น 12 ชั่วโมง

ใช้ DATE_FORMAT() กับ pattern %l:%i %p

คำสั่ง MySQL

mysql> SELECT CONCAT('The change Format in 12 Hours in MySQL=', 
    -> DATE_FORMAT('2019-03-12 20:55:00', '%l:%i %p')) AS OriginalTimeFormat;

ผลลัพธ์

+------------------------------------------------+
| OriginalTimeFormat                             |
+------------------------------------------------+
| The change Format in 12 Hours in MySQL=8:55 PM |
+------------------------------------------------+

ตาราง Format Specifiers สำคัญ

Specifierความหมายตัวอย่าง
%Hชั่วโมง 24h (00-23)20
%h / %Iชั่วโมง 12h (01-12)08
%lชั่วโมง 12h ไม่มี leading zero (1-12)8
%iนาที (00-59)55
%sวินาที (00-59)00
%pAM/PMPM

แปลงระหว่าง TIMESTAMP และ DATETIME

-- UNIX timestamp -> DATETIME
SELECT FROM_UNIXTIME(1551637800);

-- DATETIME -> UNIX timestamp
SELECT UNIX_TIMESTAMP('2019-03-04 12:00:00');

แนวทางปฏิบัติที่ดี: เก็บเวลาใน UTC (TIMESTAMP หรือ DATETIME) แปลง timezone ตอนแสดงผลเท่านั้น