0

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

$_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
4

2 回答 2

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');
}

演示

于 2014-04-26T18:38:56.190 回答
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该类将使克隆/修改部分更加整洁。

于 2014-04-26T18:55:10.617 回答