原文提供的自定義函數 getTime() 邏輯繁瑣且存在缺陷(如 date('h') 返回 12 小時制導致判斷錯誤)。現代 PHP 應直接使用 DateTime 物件或 date('H:i:s') 格式化字符獲取 24 小時制時間,簡潔且零 Bug。
function getTime() {
$h1 = date('h') > 12 ? (date('h') - 12) : date('h'); // date('h') 範圍 01-12,永遠不大於 12!
$h2 = ((date('h') + 12) >= 24) ? date('h') : (date('h') + 12); // 邏輯錯誤
// ...
}
date('h') 返回 01-12,永遠不會大於 12,導致上午/下午判斷完全失效。
<?php
// 設置時區(必須)
date_default_timezone_set('Asia/Shanghai');
// 24小時制完整時間
echo date('Y-m-d H:i:s'); // 2024-01-15 14:30:59
// 僅時間部分
echo date('H:i:s'); // 14:30:59
echo date('G:i:s'); // 14:30:59 (無前導零)
?>
<?php
$dt = new DateTime('now', new DateTimeZone('Asia/Shanghai'));
echo $dt->format('Y-m-d H:i:s'); // 2024-01-15 14:30:59
// 修改時間
$dt->modify('+1 day');
echo $dt->format('Y-m-d H:i:s');
// 時區轉換
$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->format('Y-m-d H:i:s'); // UTC 時間
?>
<?php
$timestamp = time(); // 當前時間戳
echo date('Y-m-d H:i:s', $timestamp); // 格式化
// 從字串解析
$ts = strtotime('2024-01-15 14:30:00');
echo date('Y-m-d H:i:s', $ts);
?>
<?php
/**
* 獲取格式化的 24 小時制時間字串
* @param string $format 格式,默認完整日期時間
* @param int|null $timestamp 時間戳,默認當前
* @param string|DateTimeZone $timezone 時區,默認 Asia/Shanghai
* @return string
*/
function get24Time(string $format = 'Y-m-d H:i:s', $timestamp = null, $timezone = 'Asia/Shanghai'): string {
$dt = $timestamp ? new DateTime("@$timestamp") : new DateTime('now');
$dt->setTimezone(new DateTimeZone($timezone));
return $dt->format($format);
}
// 使用範例
echo get24Time(); // 2024-01-15 14:30:59
echo get24Time('H:i'); // 14:30
echo get24Time('Y-m-d H:i:s', strtotime('-1 hour')); // 1小時前
echo get24Time('Y-m-d H:i:s', null, 'UTC'); // UTC 時間
?>
<?php
function relativeTime(int $timestamp): string {
$diff = time() - $timestamp;
if ($diff < 60) return '剛剛';
if ($diff < 3600) return floor($diff/60) . '分鐘前';
if ($diff < 86400) return floor($diff/3600) . '小時前';
if ($diff < 172800) return '昨天 ' . date('H:i', $timestamp);
return date('m-d H:i', $timestamp);
}
?>
<?php
$todayStart = strtotime('today'); // 今天 00:00:00
$todayEnd = strtotime('tomorrow') - 1; // 今天 23:59:59
// 或用 DateTime
$dt = new DateTime('today', new DateTimeZone('Asia/Shanghai'));
$todayStart = $dt->getTimestamp();
$dt->modify('tomorrow -1 second');
$todayEnd = $dt->getTimestamp();
?>
H/G 格式化字符date_default_timezone_set('Asia/Shanghai') 或 DateTimeZone現代 PHP 日期時間處理,DateTime + DateTimeZone + date() 格式化字符,是專業、可維護、無 Bug 的標準組合拳。