PHP 中日期時間運算主要通過 strtotime() 和 date() 函數組合實現,靈活且強大。
// 當前日期
$today = date('Y-m-d');
// 加 2 天
$twoDaysLater = date("Y-m-d", strtotime("$today + 2 days"));
// 減 1 週
$oneWeekAgo = date("Y-m-d", strtotime("$today - 1 week"));
// 下個月第一天
$nextMonthFirst = date("Y-m-01", strtotime("+1 month"));
// 本月最後一天
$lastDayOfMonth = date("Y-m-t", strtotime("$today"));
// 指定日期加減
$specificDate = '2024-01-15';
$tenDaysLater = date("Y-m-d", strtotime("$specificDate + 10 days"));
| 需求 | strtotime 參數示例 |
|---|---|
| 明天 | +1 day / tomorrow |
| 後天 | +2 days |
| 上週一 | last monday |
| 下個月 | +1 month / next month |
| 去年同期 | -1 year |
| 具體時間 | +3 hours 30 minutes |
// 獲取時間戳
$timestamp = strtotime('2024-12-25 10:30:00');
// 格式化輸出
echo date('Y-m-d H:i:s', $timestamp); // 2024-12-25 10:30:00
echo date('l, F j, Y', $timestamp); // Wednesday, December 25, 2024
// 計算兩日期差值(天數)
$diff = abs(strtotime('2024-12-31') - strtotime('2024-12-01'));
$days = floor($diff / (60 * 60 * 24)); // 30 天
// 判斷是否為閏年
$isLeap = date('L', strtotime('2024-01-01')); // 1 表示閏年
// 獲取星期幾 (0-6, 0為週日)
$weekday = date('w', strtotime('2024-12-25'));
PHP 5.2+ 推薦使用面向對象的 DateTime 類,功能更強大、時區處理更完善:
$date = new DateTime('2024-12-01');
$date->modify('+2 weeks');
echo $date->format('Y-m-d'); // 2024-12-15
// 時區處理
$date = new DateTime('now', new DateTimeZone('Asia/Taipei'));
echo $date->format('Y-m-d H:i:s');