date() 格式化配合 strtotime() 解析是 PHP 日期運算的黃金搭檔。本文匯總最常用的日期計算模式,提供可直接複製使用的代碼片段。
<?php
// date(格式字符串, 時間戳)
// strtotime(相對時間描述, 基準時間戳)
echo date("Y-m-d"); // 今天
echo date("Y-m-d", strtotime("-1 day")); // 昨天
echo date("Y-m-d", strtotime("+1 day")); // 明天
?>
| 需求 | 代碼 | 輸出示例 |
|---|---|---|
| 今天 | date("Y-m-d") | 2024-01-15 |
| 昨天 | date("Y-m-d", strtotime("-1 day")) | 2024-01-14 |
| 明天 | date("Y-m-d", strtotime("+1 day")) | 2024-01-16 |
| 一周後 | date("Y-m-d", strtotime("+1 week")) | 2024-01-22 |
| 一周零兩天四小時兩秒後 | date("Y-m-d G:i:s", strtotime("+1 week 2 days 4 hours 2 seconds")) | 2024-01-24 18:30:47 |
| 下個星期四 | date("Y-m-d", strtotime("next Thursday")) | 2024-01-18 |
| 上個周一 | date("Y-m-d", strtotime("last Monday")) | 2024-01-08 |
| 一個月前 | date("Y-m-d", strtotime("last month")) | 2023-12-15 |
| 一個月後 | date("Y-m-d", strtotime("+1 month")) | 2024-02-15 |
| 十年後 | date("Y-m-d", strtotime("+10 year")) | 2034-01-15 |
<?php
// 基準時間
strtotime("2024-01-15"); // 指定日期
strtotime("2024-01-15 14:30:00"); // 指定日期時間
// 複雜組合
strtotime("first day of +2 months"); // 兩個月後的 1 號
strtotime("last day of this month"); // 本月最後一天
strtotime("third wednesday of July 2024"); // 2024年7月第三個周三
// 邊界情況注意
strtotime("+1 month", strtotime("2024-01-31")); // 2024-03-02 (非 2月31日)
strtotime("last day of +1 month", strtotime("2024-01-31")); // 2024-02-29 (正確)
?>
<?php
// 英文星期
echo date("l"); // Monday (全稱)
echo date("D"); // Mon (縮寫)
// 數字星期 (0=周日, 1=周一...6=周六)
echo date("w"); // 1
echo date("N"); // 1 (ISO-8601: 1=周一...7=周日)
// 中文星期
$week = ["日", "一", "二", "三", "四", "五", "六"];
echo "星期" . $week[date("w")]; // 星期一
echo "星期" . $week[date("w", strtotime("2024-01-15"))]; // 指定日期
// 判斷周末
$isWeekend = in_array(date("w"), [0, 6]);
?>
<?php
class DateHelper {
// 獲取日期範圍
public static function getDateRange($start, $end, $format = 'Y-m-d') {
$dates = [];
$current = strtotime($start);
$endTs = strtotime($end);
while ($current <= $endTs) {
$dates[] = date($format, $current);
$current = strtotime("+1 day", $current);
}
return $dates;
}
// 友好時間顯示 (如: 3分鐘前、2小時前、昨天、3天前)
public static function humanTime($timestamp) {
$diff = time() - $timestamp;
if ($diff < 60) return "{$diff}秒前";
if ($diff < 3600) return floor($diff/60) . "分鐘前";
if ($diff < 86400) return floor($diff/3600) . "小時前";
if ($diff < 604800) return floor($diff/86400) . "天前";
return date("Y-m-d", $timestamp);
}
// 年齡計算
public static function getAge($birthDate) {
$birth = new DateTime($birthDate);
$today = new DateTime('today');
return $birth->diff($today)->y;
}
}
// 使用
var_dump(DateHelper::getDateRange('2024-01-01', '2024-01-05'));
echo DateHelper::humanTime(strtotime('-2 hours')); // 2小時前
echo DateHelper::getAge('1990-05-20'); // 33
?>
date.timezone = Asia/Shanghai 或代碼 date_default_timezone_set()strtotime() 自動處理,但跨夏令時邊界計算需謹慎