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

PHP date() 與 strtotime() 日期時間操作完全指南

     編輯:PHP 綜合知識

兩大核心函數速覽

函數輸入輸出典型用途
date()格式字串 + 時間戳格式化日期字串顯示、記錄、輸出
strtotime()英文自然語言時間描述Unix 時間戳 (整數)相對時間計算、解析

時區設定:必做第一步

<?php
// 設定預設時區(建議放在 bootstrap/配置檔)
date_default_timezone_set('Asia/Taipei'); // 或 Asia/Shanghai
// 等同於 ini_set('date.timezone', 'Asia/Taipei');

相對時間計算實戰速查表

<?php
$now = time(); // 當前時間戳

// 昨天 / 明天
date('Y-m-d', strtotime('yesterday'));
date('Y-m-d', strtotime('tomorrow'));

// 相對天數
date('Y-m-d', strtotime('-1 day'));   // 昨天
date('Y-m-d', strtotime('-3 days'));  // 3 天前
date('Y-m-d', strtotime('+7 days'));  // 7 天后

// 週邊計算
date('Y-m-d', strtotime('monday this week'));     // 本週一
date('Y-m-d', strtotime('next monday'));          // 下週一
date('Y-m-d', strtotime('last friday'));          // 上週五

// 月份邊界(極實用!)
date('Y-m-d', strtotime('first day of this month'));   // 本月 1 號
date('Y-m-d', strtotime('last day of this month'));    // 本月最後一天
date('Y-m-d', strtotime('first day of next month'));   // 下月 1 號
date('Y-m-d', strtotime('last day of next month'));    // 下月最後一天
date('Y-m-d', strtotime('last day of -1 month'));      // 上月最後一天

// 年份邊界
date('Y-m-d', strtotime('first day of January this year'));
date('Y-m-d', strtotime('last day of December this year'));

// 固定格式解析
strtotime('2024-12-25');           // 標準日期
strtotime('2024-12-25 14:30:00');  // 日期時間
strtotime('14:30');                // 今日指定時間

進階技巧

1. 計算兩日期差異(天數)

<?php
$start = strtotime('2024-01-01');
$end   = strtotime('2024-12-31');
$diffDays = ($end - $start) / 86400; // 365

2. 判斷是否為今天/本週/本月

<?php
function isToday($timestamp) {
    return date('Y-m-d', $timestamp) === date('Y-m-d');
}

function isThisWeek($timestamp) {
    $weekStart = strtotime('monday this week');
    $weekEnd = strtotime('sunday this week');
    return $timestamp >= $weekStart && $timestamp <= $weekEnd;
}

3. 避開 strtotime 陷阱

  • strtotime('+1 month') 在 1/31 會得到 3/3(非 2/28),推薦用 'first day of +1 month'
  • 兩位數年份:strtotime('24-01-01') 視為 2024,strtotime('99-01-01') 視為 1999
  • 非英文環境下月份名稱解析會失敗,請改用 DateTime 類

現代化替代:DateTime 類(PHP 5.2+)

<?php
$dt = new DateTime('now', new DateTimeZone('Asia/Taipei'));

// 修改日期
$dt->modify('+3 days');
$dt->modify('last day of next month');

// 格式化輸出
echo $dt->format('Y-m-d H:i:s');

// 計算差值
$dt1 = new DateTime('2024-01-01');
$dt2 = new DateTime('2024-12-31');
$interval = $dt1->diff($dt2);
echo $interval->days; // 365
echo $interval->format('%a 天 %h 小時 %i 分');

總結

  • 簡單格式化:date() + strtotime() 最快
  • 複雜運算/跨時區/國際化:首選 DateTime / DateTimeImmutable
  • 專案統一在入口檔設定 date_default_timezone_set()
  • 資料庫存儲統一用 TIMESTAMP 或 DATETIME(UTC),應用層再轉換顯示時區
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved