萬盛學電腦網

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

PHP 時間戳運算:獲取今日/昨日/明日 00:00:00 與 23:59:59 的標準化函數

業務邏輯中頻繁需要「今天範圍」、「昨天範圍」、「明天範圍」的時間戳邊界。本文提供標準化、可測試、無時區陷阱的工具函數實現。

核心函數:基於「今天 00:00:00」推導周邊範圍

<?php
/**
 * 獲取指定基準日 (00:00:00 時間戳) 的前後三天範圍
 * @param int $dayStartTimestamp 當天 00:00:00 的時間戳
 * @return array ['yesterday'=>[start,end], 'today'=>[start,end], 'tomorrow'=>[start,end]]
 */
function getDayRanges(int $dayStartTimestamp): array {
    const DAY_SECONDS = 86400;  // 24 * 3600
    
    $todayStart = $dayStartTimestamp;
    $todayEnd = $todayStart + DAY_SECONDS - 1;  // 23:59:59
    
    $yesterdayStart = $todayStart - DAY_SECONDS;
    $yesterdayEnd = $todayStart - 1;
    
    $tomorrowStart = $todayStart + DAY_SECONDS;
    $tomorrowEnd = $tomorrowStart + DAY_SECONDS - 1;
    
    return [
        'yesterday' => [$yesterdayStart, $yesterdayEnd],
        'today'     => [$todayStart, $todayEnd],
        'tomorrow'  => [$tomorrowStart, $tomorrowEnd],
    ];
}

/** 獲取「今天 00:00:00」時間戳 (時區感知) */
function getTodayStart(string $timezone = 'Asia/Shanghai'): int {
    $dt = new DateTime('today', new DateTimeZone($timezone));
    return (int)$dt->format('U');
}

// 使用示例
$todayStart = getTodayStart();  // 當前時區的今天 00:00:00
$ranges = getDayRanges($todayStart);

echo "昨天: " . date('Y-m-d H:i:s', $ranges['yesterday'][0]) . " ~ " . date('Y-m-d H:i:s', $ranges['yesterday'][1]) . "\n";
echo "今天: " . date('Y-m-d H:i:s', $ranges['today'][0]) . " ~ " . date('Y-m-d H:i:s', $ranges['today'][1]) . "\n";
echo "明天: " . date('Y-m-d H:i:s', $ranges['tomorrow'][0]) . " ~ " . date('Y-m-d H:i:s', $ranges['tomorrow'][1]) . "\n";

/*
輸出示例 (假設今天 2024-01-15):
昨天: 2024-01-14 00:00:00 ~ 2024-01-14 23:59:59
今天: 2024-01-15 00:00:00 ~ 2024-01-15 23:59:59
明天: 2024-01-16 00:00:00 ~ 2024-01-16 23:59:59
*/

進階封裝:DateRange 值對象

<?php
readonly class DateRange {
    public function __construct(
        public int $startTimestamp,
        public int $endTimestamp,
        public string $timezone
    ) {}
    
    public function contains(int $timestamp): bool {
        return $timestamp >= $this->startTimestamp && $timestamp <= $this->endTimestamp;
    }
    
    public function toDateTimeImmutable(): array {
        $tz = new DateTimeZone($this->timezone);
        return [
            'start' => DateTimeImmutable::createFromFormat('U', (string)$this->startTimestamp, $tz),
            'end' => DateTimeImmutable::createFromFormat('U', (string)$this->endTimestamp, $tz),
        ];
    }
    
    public function __toString(): string {
        [$start, $end] = $this->toDateTimeImmutable();
        return $start->format('Y-m-d H:i:s') . ' ~ ' . $end->format('Y-m-d H:i:s');
    }
}

class DayRangeFactory {
    public function __construct(private string $defaultTimezone = 'Asia/Shanghai') {}
    
    public function createToday(): DateRange {
        $start = (new DateTime('today', new DateTimeZone($this->defaultTimezone)))->getTimestamp();
        $end = $start + 86399;
        return new DateRange($start, $end, $this->defaultTimezone);
    }
    
    public function createYesterday(): DateRange {
        $start = (new DateTime('yesterday', new DateTimeZone($this->defaultTimezone)))->getTimestamp();
        $end = $start + 86399;
        return new DateRange($start, $end, $this->defaultTimezone);
    }
    
    public function createTomorrow(): DateRange {
        $start = (new DateTime('tomorrow', new DateTimeZone($this->defaultTimezone)))->getTimestamp();
        $end = $start + 86399;
        return new DateRange($start, $end, $this->defaultTimezone);
    }
    
    public function createFromDate(string $date): DateRange {
        $start = (new DateTime($date, new DateTimeZone($this->defaultTimezone)))->getTimestamp();
        $end = $start + 86399;
        return new DateRange($start, $end, $this->defaultTimezone);
    }
}

// 使用
$factory = new DayRangeFactory('Asia/Shanghai');
$today = $factory->createToday();
$yesterday = $factory->createYesterday();

$sql = "SELECT * FROM orders WHERE created_at BETWEEN {$today->startTimestamp} AND {$today->endTimestamp}";
// 或配合 DateTimeImmutable
[$start, $end] = $today->toDateTimeImmutable();
$query->andWhere('created_at >= :start')->setParameter('start', $start)
      ->andWhere('created_at <= :end')->setParameter('end', $end);

時區陷阱與最佳實踐

陷阱錯誤代碼正確代碼
依賴服務器時區date('Y-m-d 00:00:00')new DateTime('today', new DateTimeZone('Asia/Shanghai'))
strtotime 解析歧義strtotime('today')new DateTime('today', $tz)->getTimestamp()
夏令時邊界固定 86400 秒DateTime::add(new DateInterval('P1D')) 自動處理
跨時區業務硬編碼 +8 小時用戶級時區存儲,查詢時轉換

常用查詢範圍快捷函數

<?php
function getWeekRange(int $timestamp, int $weekStart = 1): array {  // 1=週一, 0=週日
    $dt = DateTimeImmutable::createFromFormat('U', (string)$timestamp, new DateTimeZone('UTC'));
    $dt = $dt->setTimezone(new DateTimeZone('Asia/Shanghai'));
    $dow = (int)$dt->format('N');  // 1-7
    $diff = $dow - $weekStart;
    if ($diff < 0) $diff += 7;
    $weekStartDt = $dt->sub(new DateInterval("P{$diff}D"))->setTime(0,0,0);
    $weekEndDt = $weekStartDt->add(new DateInterval('P6D'))->setTime(23,59,59);
    return [$weekStartDt->getTimestamp(), $weekEndDt->getTimestamp()];
}

function getMonthRange(int $timestamp): array {
    $dt = DateTimeImmutable::createFromFormat('U', (string)$timestamp, new DateTimeZone('UTC'))
        ->setTimezone(new DateTimeZone('Asia/Shanghai'));
    $start = $dt->modify('first day of this month')->setTime(0,0,0)->getTimestamp();
    $end = $dt->modify('last day of this month')->setTime(23,59,59)->getTimestamp();
    return [$start, $end];
}

function getQuarterRange(int $timestamp): array {
    $dt = DateTimeImmutable::createFromFormat('U', (string)$timestamp, new DateTimeZone('UTC'))
        ->setTimezone(new DateTimeZone('Asia/Shanghai'));
    $month = (int)$dt->format('n');
    $quarter = (int)ceil($month / 3);
    $startMonth = ($quarter - 1) * 3 + 1;
    $start = $dt->setDate($dt->format('Y'), $startMonth, 1)->setTime(0,0,0)->getTimestamp();
    $end = $dt->setDate($dt->format('Y'), $startMonth + 3, 1)->sub(new DateInterval('PT1S'))->getTimestamp();
    return [$start, $end];
}

總結

時間邊界計算核心原則:以「當天 00:00:00」為基準,加減 86400 秒推導。生產代碼必須:顯式指定時區、使用 DateTimeImmutable 避免副作用、封裝為值對象、統一輸出格式。拒絕手動拼接字符串、拒絕 strtotime 相對時間、拒絕硬編碼時區偏移。

copyright © 萬盛學電腦網 all rights reserved