从两个日期时间变量创建开始和结束日期时间的数组

时间:2017-09-25 07:14:57

标签: php arrays datetime

我有一个开始和结束DateTime对象,并希望迭代它们以获得每天开始和结束的数组。为了迭代它,我编写了这个函数:

public function getDatesBetweenTwoDates($start = null, $end = null)
{
    return iterator_to_array(new \DatePeriod($start, new \DateInterval('P1D'), $end));
}

但是,此函数返回一个这样的数组,不支持时间:

['2017-10-01', '2017-10-02', ...]

我需要的是这样的事情:

输入:

$start = new DateTime("2017-10-01 10:00:00");
$end = new DateTime("2017-10-03 19:00:00");

输出:

[
    [
        'start' => '2017-10-01 10:00:00',
        'end' => '2017-10-01 23:59:59'
    ],
    [
        'start' => '2017-10-02 00:00:00',
        'end' => '2017-10-02 23:59:59'
    ],
    [
        'start' => '2017-10-03 00:00:00',
        'end' => '2017-10-03 19:00:00'
    ],
]

任何提示或帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

我看到你需要迭代你的数组并用新格式重新创建日期数组

$start = new DateTime("2017-10-01 10:00:00");
$end = new DateTime("2017-10-03 19:00:00");

$datesArray = iterator_to_array(new \DatePeriod($start, new \DateInterval('P1D'), $end));

array_walk($datesArray, function ($value, $key) use (&$dates, $start, $end) {

    $dates[$key]['start'] = (
        ($key == 0) ? $value->format('Y-m-d H:i:s') : $value->setTime(00, 0, 00)->format('Y-m-d H:i:s')
    );

    $endDate = $value->setTime(23, 59, 59);

    if ($endDate->getTimestamp() > $end->getTimestamp()) {
        $endDate = $end;
    }

    $dates[$key]['end'] = $endDate->format('Y-m-d H:i:s');


});
print_r($dates);

这将输出:

Array
(
    [0] => Array
        (
            [start] => 2017-10-01 10:00:00
            [end] => 2017-10-01 23:59:59
        )

    [1] => Array
        (
            [start] => 2017-10-02 00:00:00
            [end] => 2017-10-02 23:59:59
        )

    [2] => Array
        (
            [start] => 2017-10-03 00:00:00
            [end] => 2017-10-03 19:00:00
        )

)

实时样本:https://3v4l.org/UnDcA

注意:正如您在3v4l所见,如果您将使用HHVM,您将获得不同/错误的输出。

答案 1 :(得分:-1)

这应该有效:

<?php
 $start = "start_date";
 $end = "end_date";
 $date = array("start"=>$start, "end"=>$end);
 $dates = array();
 array_push($dates, $date);
 print_r($dates);
?>