萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 日期時間運算:取得下一週、下個月、明年等相對時間

核心函數: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 設定正確。
  • PHP 8.1+ 建議改用 DateTimeImmutable 物件導向介面,更安全、鏈式操作更清晰。
copyright © 萬盛學電腦網 all rights reserved