计算按日/小时分组的两个日期之间的分钟

时间:2016-11-08 18:02:54

标签: php date-difference

我有以下数组:

$periods = array(
    ['begin' => '2013-08-14 10:00:00', 'end' => '2013-08-14 11:30:00'],
    ['begin' => '2013-08-14 11:40:00', 'end' => '2013-08-14 11:45:00'],
    ['begin' => '2013-08-14 11:45:00', 'end' => '2013-08-14 11:52:00'],
    ['begin' => '2013-08-08 07:00:00', 'end' => '2013-08-08 09:25:00'],
    ['begin' => '2013-08-09 23:50:00', 'end' => '2013-08-10 00:25:00']
);

我想要的是按天/小时计算每个时段分组之间的分钟数,以得到类似的结果:

date                  minutes
2013-08-14 10:00:00 : 60
2013-08-14 11:00:00 : 42
2013-08-08 07:00:00 : 60
2013-08-08 08:00:00 : 60
2013-08-08 09:00:00 : 25
2013-08-09 23:00:00 : 10
2013-08-10 00:00:00 : 25

1 个答案:

答案 0 :(得分:0)

好的,我明白了。

数组:

$periods = array(
    ['begin' => '2013-08-14 10:00:00', 'end' => '2013-08-14 11:30:00'],
    ['begin' => '2013-08-14 11:40:00', 'end' => '2013-08-14 11:45:00'],
    ['begin' => '2013-08-14 11:45:00', 'end' => '2013-08-14 11:52:00'],
    ['begin' => '2013-08-08 07:00:00', 'end' => '2013-08-08 09:25:00'],
    ['begin' => '2013-08-09 23:50:00', 'end' => '2013-08-10 00:25:00']
);

代码:

$period_difference = array();
foreach ($intervals as $interval) {
    $dateTimes = new DatePeriod(
        new DateTime($interval['begin']),
        new DateInterval('PT1M'),
        new DateTime($interval['end'])
    );

    foreach ($dateTimes as $dt) {
        $period_difference[$dt->format('Y-m-d H:00:00')] = isset($period_difference[$dt->format('Y-m-d H:00:00')]) ? $period_difference[$dt->format('Y-m-d H:00:00')]+1 : 1;
    }
}

在phpio.net上进行测试:http://phpio.net/s/idl