strtotime() 相對格式strtotime() 支援豐富的英文相對時間描述,配合 date() 格式化,輕鬆完成各類日期運算。
<?php
$now = time(); // 當前時間戳
// 以 Y-m-d H:i:s 格式輸出
$format = 'Y-m-d H:i:s';
echo '當前時間: ' . date($format, $now) . PHP_EOL;
echo '1 秒後: ' . date($format, strtotime('+1 second', $now)) . PHP_EOL;
echo '1 分鐘後: ' . date($format, strtotime('+1 minute', $now)) . PHP_EOL;
echo '1 小時後: ' . date($format, strtotime('+1 hour', $now)) . PHP_EOL;
echo '1 天後: ' . date($format, strtotime('+1 day', $now)) . PHP_EOL;
echo '1 週後: ' . date($format, strtotime('+1 week', $now)) . PHP_EOL;
echo '1 個月後: ' . date($format, strtotime('+1 month', $now)) . PHP_EOL;
echo '1 年後: ' . date($format, strtotime('+1 year', $now)) . PHP_EOL;
// 組合用法
echo '2 週零 3 天前: ' . date($format, strtotime('-2 weeks -3 days', $now)) . PHP_EOL;
echo '下個月第一天: ' . date('Y-m-01', strtotime('first day of next month', $now)) . PHP_EOL;
echo '本月最後一天: ' . date('Y-m-t', $now) . PHP_EOL;
// 取得時間戳(而非格式化字串)
$nextMonthTimestamp = strtotime('+1 month', $now);
?>
// 包月會員:註冊時間 + 1 個月
$expireAt = date('Y-m-d H:i:s', strtotime('+1 month', $registerTime));
// 包年會員
$expireAt = date('Y-m-d H:i:s', strtotime('+1 year', $registerTime));
// 試用 7 天
$trialEnd = date('Y-m-d H:i:s', strtotime('+7 days', $registerTime));
+1 month 在 1 月 31 日會得到 3 月 3 日(因 2 月無 31 日),若需「同一天」邏輯請用 'first day of next month' 或手動處理。date_default_timezone_set('Asia/Taipei') 或 php.ini 設定正確。DateTimeImmutable 物件導向介面,更安全、鏈式操作更清晰。