在 PHP 開發中,根據相對時間輸出特定日期(如「前一天」、「下個月」、「兩小時後」)是常見需求。結合 strtotime() 與 date() 函數,即可輕鬆實現任意時間點的計算與格式化輸出。
<?php
// 設定時區(必須,避免時區偏差)
date_default_timezone_set('Asia/Shanghai');
// 取得前一天的日期時間
$a = date('Y-m-d H:i:s', strtotime('-1 day'));
echo $a; // 輸出格式:2024-01-15 14:30:00
?>
strtotime() 支援豐富的自然語言時間描述:
| 語法 | 含義 | 範例 |
|---|---|---|
-1 year / +1 year | 前一年 / 明年 | strtotime('-1 year') |
-1 month / +1 month | 上個月 / 下個月 | strtotime('+1 month') |
-1 day / +1 day | 昨天 / 明天 | strtotime('-1 day') |
-1 hour / +1 hour | 一小時前 / 一小時後 | strtotime('+1 hour') |
-1 minute / +1 minute | 一分鐘前 / 一分鐘後 | strtotime('-1 minute') |
-1 second / +1 second | 一秒前 / 一秒後 | strtotime('+1 second') |
next Monday | 下週一 | strtotime('next Monday') |
last Friday | 上週五 | strtotime('last Friday') |
first day of this month | 本月第一天 | strtotime('first day of this month') |
last day of next month | 下月最後一天 | strtotime('last day of next month') |
<?php
// 只輸出日期
echo date('Y-m-d', strtotime('-1 week')); // 一週前
echo date('Y-m-d', strtotime('+2 weeks')); // 兩週後
// 只輸出時間
echo date('H:i:s', strtotime('-30 minutes')); // 30分鐘前
// 自訂格式
echo date('Y年m月d日 H點i分', strtotime('+1 year')); // 一年後(中文格式)
?>
<?php
$now = time(); // 當前時間戳
echo date('Y-m-d H:i:s', $now - 86400); // 24小時前(86400秒)
echo date('Y-m-d H:i:s', $now + 3600); // 1小時後
echo date('Y-m-d H:i:s', strtotime('+3 days', $now)); // 3天後(指定基準時間)
?>
<?php
// 會員到期提醒:7天前發送通知
$expiry = strtotime('2024-12-31 23:59:59');
$remind = strtotime('-7 days', $expiry);
if (time() >= $remind && time() < $expiry) {
echo "發送續費提醒通知";
}
// 文章發布時間顯示「X天前」
$publishTime = strtotime('2024-01-10 10:00:00');
$diff = time() - $publishTime;
$days = floor($diff / 86400);
echo "發布於 $days 天前";
// 更完整的相對時間顯示請參考文章 ID 154225
?>
php.ini 或代碼開頭設定 date_default_timezone_set(),否則會使用伺服器預設時區導致偏差strtotime() 會自動處理,但需確認時區資料庫更新DateTime 類別date() 格式參數區分大小寫(m=月份,M=英文月份縮寫)PHP 5.2+ 建議使用物件導向的 DateTime,功能更強大、避免 32 位限制:
<?php
$dt = new DateTime('now', new DateTimeZone('Asia/Shanghai'));
$dt->modify('-1 day');
echo $dt->format('Y-m-d H:i:s');
// 連續修改
$dt = new DateTime();
$dt->modify('+1 week')->modify('+3 hours')->modify('-15 minutes');
echo $dt->format('Y-m-d H:i:s');
?>
掌握 strtotime() 相對時間語法與 date() 格式化,配合正確時區設定,即可滿足 90% 以上的日期時間運算需求。複雜場景建議升級使用 DateTime 類別,獲得更好的可讀性與擴展性。