核心函數速查
| 函數 | 用途 | 關鍵參數 |
mktime() | 取得指定日期的 Unix 時間戳 | 時、分、秒、月、日、年 |
strtotime() | 解析英文文字日期為時間戳 | 相對時間字串("+1 week")、基準時間 |
date() | 格式化時間戳為可讀字串 | 格式字串("Y-m-d H:i:s")、時間戳 |
date_default_timezone_set() | 設定預設時區(必要) | 時區識別碼("Asia/Taipei") |
五大實戰場景
1. 兩日期相差天數(無資料庫)
$start = strtotime('2015-09-05');
$end = strtotime('2015-09-18');
$days = ($end - $start) / 86400; // 86400 = 60*60*24
echo $days; // 13
2. 計算年齡/週數/月數/年數(含閏年處理)
date_default_timezone_set('Asia/Taipei');
$birth = '2005-11-03 10:08';
$days = ceil(abs(time() - strtotime($birth)) / 86400);
$weeks = floor($days / 7);
$months = (date('Y') - date('Y', strtotime($birth))) * 12
+ date('m') - date('m', strtotime($birth));
$years = date('Y') - date('Y', strtotime($birth))
+ (date('md') >= date('md', strtotime($birth)) ? 0 : -1);
3. 取得「明天、下個月、明年」同一天
$tomorrow = date('Y-m-d', strtotime('+1 day'));
$nextMonth = date('Y-m-d', strtotime('+1 month'));
$nextYear = date('Y-m-d', strtotime('+1 year'));
4. 計算工作時數(排除週末與國定假日)
$holidays = ['01-01','02-28','05-01','10-10']; // 範例
$start = strtotime('2024-01-01');
$end = strtotime('2024-12-31');
$hours = 0;
for ($t = $start; $t <= $end; $t += 86400) {
$w = (int)date('w', $t); // 0=Sun, 6=Sat
$md = date('m-d', $t);
if ($w === 0 || $w === 6) continue; // 週末
if (in_array($md, $holidays)) continue; // 國定假日
$hours += 8; // 每日 8 小時
}
echo "總工時:$hours";
5. 秒數轉換為「時/分/秒」易讀格式
function secToHMS(int $sec): string {
$h = floor($sec / 3600);
$m = floor(($sec % 3600) / 60);
$s = $sec % 60;
return sprintf('%02d:%02d:%02d', $h, $m, $s);
}
echo secToHMS(3231803); // 897:43:23
常見坑與最佳實務
- 時區必須設定:未設時區會觸發
E_WARNING,且結果可能偏移數小時。
- 優先用
DateTime 類別(PHP 5.2+):物件導向、支援時區物件、鏈式呼叫,避免 32 位元系統 2038 年問題。
- 資料庫存儲用 UTC:儲存
TIMESTAMP 或 DATETIME 皆以 UTC,顯示時再轉換使用者時區。