首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 日期時間運算:獲取下周、下月、下年的標準姿勢

     編輯:PHP 綜合知識

核心函數:strtotime() 相對時間格式

PHP strtotime() 支持豐富的英文相對時間描述,是日期運算的首選工具。配合 date() 格式化輸出,可輕鬆實現各類時間計算。

基礎語法

// 當前時間 + 間隔
date('Y-m-d H:i:s', strtotime('+1 month'));   // 下個月同一時間
date('Y-m-d H:i:s', strtotime('+1 week'));    // 下周同一時間
date('Y-m-d H:i:s', strtotime('+1 year'));    // 下年同一時間
date('Y-m-d H:i:s', strtotime('+1 day'));     // 明天同一時間

// 也支持複合表達
strtotime('+2 weeks 3 days 5 hours');

完整單位對照表

單位英文關鍵字示例
秒second / seconds / sec+30 seconds
分minute / minutes / min+15 minutes
時hour / hours+3 hours
天day / days+7 days
周week / weeks+2 weeks
月month / months+1 month
年year / years+1 year
工作日weekday / weekdays+5 weekdays (跳過周末)
特定星期幾monday / tuesday ...next monday (下個周一)
月初/月末first day of / last day offirst day of next month

實戰場景:會員到期時間計算

function getExpiryDate($startDate, $plan) {
    $base = is_int($startDate) ? $startDate : strtotime($startDate);
    switch ($plan) {
        case 'monthly':  $expr = '+1 month';  break;
        case 'quarterly': $expr = '+3 months'; break;
        case 'yearly':   $expr = '+1 year';   break;
        case 'weekly':   $expr = '+1 week';   break;
        default: throw new InvalidArgumentException('未知套餐');
    }
    return date('Y-m-d H:i:s', strtotime($expr, $base));
}

// 使用
echo getExpiryDate('2024-01-15', 'monthly');  // 2024-02-15 00:00:00
echo getExpiryDate(time(), 'yearly');         // 明年今日

時間戳互轉

// 日期字符串 -> 時間戳
$ts = strtotime('2024-12-31 23:59:59');

// 時間戳 -> 格式化日期
echo date('Y-m-d H:i:s', $ts);

// 獲取「下個月同一天」的時間戳 (一步到位)
$nextMonthTs = strtotime('+1 month', $ts);

邊界情況與避坑指南

  • 月末日期溢出:strtotime('+1 month', strtotime('2024-01-31')) 返回 2024-03-03 (因 2 月無 31 號)。解決:用 'last day of +1 month' 固定取月末,或 'first day of +1 month' 取月初。
  • 時區影響:確保 date_default_timezone_set('Asia/Shanghai') 或 php.ini 設置正確,否則跨天計算可能偏移。
  • 夏令時 (DST):涉及具體小時運算時,DateTime 類比 strtotime 處理更精準。
  • PHP 8.1+ 推薦 DateTime:
    $dt = new DateTime('2024-01-31');
    $dt->modify('+1 month'); // 2024-02-29 (閏年) 或 03-02
    echo $dt->format('Y-m-d');

DateTime 現代化寫法 (PHP 5.2+)

$dt = new DateTime(); // 當前時間
$dt->add(new DateInterval('P1M')); // +1 月
$dt->sub(new DateInterval('P7D')); // -7 天
echo $dt->format('Y-m-d H:i:s');

// 連續操作
echo (new DateTime('+1 week'))->format('Y-m-d');

DateInterval 格式遵循 ISO 8601:P (Period) + Y/M/D + T (Time) + H/M/S。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved