date() 格式化字元完整表
| 字元 | 說明 | 範例 |
| Y | 4 位數年 | 2024 |
| y | 2 位數年 | 24 |
| m | 月份 (01-12) | 01 |
| n | 月份 (1-12) | 1 |
| F | 月份英文全名 | January |
| M | 月份英文縮寫 | Jan |
| d | 日期 (01-31) | 15 |
| j | 日期 (1-31) | 15 |
| l | 星期幾全名 | Monday |
| D | 星期幾縮寫 | Mon |
| w | 星期幾數字 (0=日) | 1 |
| N | ISO 星期幾 (1=一) | 1 |
| H | 24 小時制 (00-23) | 14 |
| h | 12 小時制 (01-12) | 02 |
| i | 分鐘 (00-59) | 30 |
| s | 秒數 (00-59) | 59 |
| a | am/pm 小寫 | pm |
| A | AM/PM 大寫 | PM |
| U | Unix 時間戳 | 1705312259 |
| c | ISO 8601 | 2024-01-15T14:30:59+08:00 |
| r | RFC 2822 | Mon, 15 Jan 2024 14:30:59 +0800 |
strtotime() 相對時間字串
strtotime('now'); // 現在
strtotime('+1 day'); // 明天
strtotime('-1 week'); // 一週前
strtotime('first day of this month'); // 本月 1 號
strtotime('last day of next month'); // 下月最後一天
strtotime('next Monday'); // 下個週一
strtotime('+3 months -2 days'); // 組合
DateTime 物件導向 API (推薦)
$dt = new DateTime('2024-01-15 14:30:00', new DateTimeZone('Asia/Taipei'));
$dt->modify('+1 day');
$dt->setTime(9, 0, 0);
echo $dt->format('Y-m-d H:i:s'); // 2024-01-16 09:00:00
// 差值
$diff = $dt1->diff($dt2);
echo $diff->days; // 天數差
echo $diff->format('%h小時%i分'); // 格式化差值
// 區間迭代
$period = new DatePeriod($start, new DateInterval('P1D'), $end);
foreach ($period as $d) { ... }
常用函式速查
| 函式 | 用途 | 回傳 |
| time() | 當前 Unix 時間戳 | int |
| microtime(true) | 含微秒的浮點時間戳 | float |
| mktime(h,i,s,m,d,Y) | 組合日期時間為時間戳 | int |
| getdate(ts) | 時間戳轉關聯陣列 | array |
| checkdate(m,d,Y) | 驗證日期合法性 | bool |
| date_default_timezone_set() | 設定預設時區 | void |
| DateTimeZone::listIdentifiers() | 列出所有时区 | array |
時區處理最佳實踐
- 程式啟動即設定:
date_default_timezone_set('Asia/Taipei');
- 資料庫儲存 **UTC** 時間戳或
DATETIME (不含時區)
- 顯示時依用戶時區轉換:
$dt->setTimezone(new DateTimeZone($userTz))
- 避免在字串拼接中混用時區
常見陷阱
strtotime('2024-02-30') 回傳 false (PHP 5.3+) 或錯誤日期 (舊版)
date('Y-m-d', strtotime('-1 month')) 在 3/31 會得到 3/03 (非 2/28),建議用 first day of -1 month
new DateTime('@'. $timestamp) 需加 @ 前綴表示 Unix 時間戳