You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP的DatePeriod中识别首次与末次迭代并调整数组

PHP DatePeriod 首尾日期时间范围设置修复方案

问题说明

遍历2023-12-01至2023-12-07的日期区间,需为首次迭代日期设置09:50:00-23:59:59时间范围,末次迭代日期设置00:00:00-13:54:00,其余日期返回空数组。

修正代码

<?php
$startDate = new DateTime('2023-12-01');
$endDate = new DateTime('2023-12-07');
$interval = new DateInterval('P1D');

// 构建包含所有目标日期的周期(需将结束日期延后一天,确保包含2023-12-07)
$period = new DatePeriod(
    $startDate,
    $interval,
    (clone $endDate)->add($interval)
);

// 将迭代器转为数组,便于判断首尾位置
$dates = iterator_to_array($period);
$totalCount = count($dates);

$result = [];
foreach ($dates as $index => $date) {
    $dateKey = $date->format('Y-m-d');
    if ($index === 0) {
        // 处理首次日期
        $result[$dateKey] = [
            'start' => $date->format('Y-m-d 09:50:00'),
            'end' => $date->format('Y-m-d 23:59:59')
        ];
    } elseif ($index === $totalCount - 1) {
        // 处理末次日期
        $result[$dateKey] = [
            'start' => $date->format('Y-m-d 00:00:00'),
            'end' => $date->format('Y-m-d 13:54:00')
        ];
    } else {
        $result[$dateKey] = [];
    }
}

print_r($result);
?>

核心修复点

  • 正确构建DatePeriod:默认传入$endDate会排除最后一天,通过克隆$endDate并添加一天作为周期终点,确保2023-12-07被包含在内。
  • 数组化迭代器:直接在DatePeriod迭代中判断首尾容易出错,转为数组后通过索引$index === 0和$index === $totalCount -1判断首尾更可靠。
  • 统一日期键格式:使用Y-m-d作为结果数组的键,避免时区或格式化差异导致的匹配问题。

预期输出

Array
(
    [2023-12-01] => Array
        (
            [start] => 2023-12-01 09:50:00
            [end] => 2023-12-01 23:59:59
        )

    [2023-12-02] => Array
        (
        )

    [2023-12-03] => Array
        (
        )

    [2023-12-04] => Array
        (
        )

    [2023-12-05] => Array
        (
        )

    [2023-12-06] => Array
        (
        )

    [2023-12-07] => Array
        (
            [start] => 2023-12-07 00:00:00
            [end] => 2023-12-07 13:54:00
        )

)

内容的提问来源于stack exchange,提问作者executable

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 15:25:17