使用DateTime创建时间间隔并将其划分为天

时间:2014-04-26 18:24:36

标签: php datetime dateinterval

我发布了开始日期和时间,以及结束日期和时间,例如:

$_POST['start_date'] //this might be 27:04:2013
$_POST['start_time'] //this might be 16:30
$_POST['end_date'] //this might be 29:04:2013
$_POST['end_time'] //this might equal 22:30

我想为发布的时间间隔延伸的每一天创建一个对象数组,这是一个DateInterval对象吗?如果是这样,那么在上面发布的值我希望得到一个包含以下

的数组
[0] 27:04:2013 16:30:00 27:04:2013 23:59:59
[1] 28 04:2014 00:00:00 28 04:2014 23:59:59 
[2] 29:04:2014 00:00:00 29:04:2014 22:30:00

2 个答案:

答案 0 :(得分:2)

$start = DateTime::createFromFormat('d:m:Y H:i', '27:04:2013 16:30');
$end   = DateTime::createFromFormat('d:m:Y H:i', '29:04:2013 22:30');
$diff  = $start->diff($end);
$pad   = ($start->format('His') > $end->format('His')) ? 2 : 1;
$days  = $diff->d + $pad;
for ($i = 1; $i <= $days; $i++) {
    if ($i === 1) {
        printf("%s %s<br>", $start->format('d:m:Y H:i:s'), $start->format('d:m:Y 23:59:59'));
    }
    else if ($i === $days) {
        printf("%s %s<br>", $end->format('d:m:Y 00:00:00'), $end->format('d:m:Y H:i:s'));
    }
    else {
        printf("%s %s<br>", $start->format('d:m:Y 00:00:00'), $start->format('d:m:Y 23:59:59'));
    }
    $start->modify('+1 day');
}

Demo

答案 1 :(得分:1)

目前尚不清楚“间隔”是否真的需要DateInterval个对象,或者每天都需要一个单独的开始/结束DateTime。无论哪种方式,下面都应该是一个明智的选择。

<?php

$start_date = '27:04:2013';
$start_time = '16:30';
$end_date = '29:04:2013';
$end_time = '22:30';

// Date input strings and generate a suitable DatePeriod
$start = DateTime::createFromFormat("d:m:Y H:i", "$start_date $start_time");
$end = DateTime::createFromFormat("d:m:Y H:i", "$end_date $end_time");
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);

foreach ($period as $date) {
    // Get midnight at start of current day
    $date_start = clone $date;
    $date_start->modify('midnight');

    // Get 23:59:59, end of current day
    // (moving to midnight of next day might be good too)
    $date_end = clone $date;
    $date_end->modify('23:59:59');

    // Take care of partial days
    $date_start = max($start, $date_start);
    $date_end = min($end, $date_end);

    // Here you would construct your array of
    // DateTime pairs, or DateIntervals, as you want.
    printf(
        "%s -> %s \n",
        $date_start->format('Y-m-d H:i'),
        $date_end->format('Y-m-d H:i')
    );
}

产生以下输出:

2013-04-27 16:30 -> 2013-04-27 23:59 
2013-04-28 00:00 -> 2013-04-28 23:59 
2013-04-29 00:00 -> 2013-04-29 22:30

<强>附录

如果你足够幸运能够使用PHP 5.5.0或更高版本,那么DateTimeImmutable类将使克隆/修改部分更加整洁。