douhuang2282 2017-09-25 07:14
浏览 46
已采纳

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

I have a start and end DateTime object and want to iterate over them to get an array of start and end per day. To iterate over it I wrote this function:

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

However, this function returns an array like this and does not support times:

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

What I need is something like this:

Input:

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

Output:

[
    [
        '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'
    ],
]

Any hint or help would be highly appreciated.

  • 写回答

2条回答 默认 最新

  • dongtuanzi1080 2017-09-25 08:01
    关注

    I see that you will need to iterate over your array and re-create the array of dates with the new format

    $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);
    

    this will output:

    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
            )
    
    )
    

    live sample : https://3v4l.org/UnDcA

    Note : as you can see at 3v4l that you will get different/wrong output if you will use HHVM.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog