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

PHP 取得昨天、今天、明天日期的多種寫法

     編輯:PHP 綜合知識

DateTime 物件導向寫法 (推薦 PHP 5.3+)

$today = new DateTime();           // 當下時間
$yesterday = (clone $today)->modify('-1 day');
$tomorrow = (clone $today)->modify('+1 day');

echo $today->format('Y-m-d');      // 2024-01-15
echo $yesterday->format('Y-m-d');
echo $tomorrow->format('Y-m-d');

// 指定時區
$tz = new DateTimeZone('Asia/Taipei');
$today = new DateTime('now', $tz);

程序式 strtotime() 寫法

echo date('Y-m-d', strtotime('-1 day'));   // 昨天
echo date('Y-m-d');                         // 今天
echo date('Y-m-d', strtotime('+1 day'));    // 明天

// 更精確:以當天 00:00:00 為基準
$todayMidnight = strtotime('today');
$yesterday = date('Y-m-d', $todayMidnight - 86400);
$tomorrow = date('Y-m-d', $todayMidnight + 86400);

常見日期格式化字元

字元說明範例
Y四位數年份2024
m兩位數月份01
d兩位數日期15
H24小時制時14
i分30
s秒05
w星期 (0=Sunday)1
W年度週數03

實用工具函式

function getDateRange(string $period): array
{
    $today = new DateTimeImmutable();
    return match ($period) {
        'today' => [$today, $today],
        'yesterday' => [$today->modify('-1 day'), $today->modify('-1 day')],
        'tomorrow' => [$today->modify('+1 day'), $today->modify('+1 day')],
        'this_week' => [
            $today->modify('monday this week'),
            $today->modify('sunday this week')
        ],
        'last_week' => [
            $today->modify('monday last week'),
            $today->modify('sunday last week')
        ],
        'this_month' => [
            $today->modify('first day of this month'),
            $today->modify('last day of this month')
        ],
        'last_month' => [
            $today->modify('first day of last month'),
            $today->modify('last day of last month')
        ],
        default => throw new InvalidArgumentException("Unknown period: $period"),
    };
}

// 使用
[$start, $end] = getDateRange('this_month');
echo $start->format('Y-m-d') . ' ~ ' . $end->format('Y-m-d');

效能與快取提示

  • DateTimeImmutable (PHP 5.5+) 避免副作用,適合函式式程式設計。
  • 大量日期運算可考慮 Carbon (Laravel 內建) 或 Chronos (CakePHP) 擴充庫。
  • 資料庫查詢日期範圍建議用 WHERE created_at >= '2024-01-01' AND created_at < '2024-02-01' (半開區間),利用索引。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved