填充两个日期之间30分钟的时间间隔

时间:2016-01-09 15:28:00

标签: php datetime

我有2个时间字符串,例如OPEN = 11:00,关闭时间是02:45

现在02:00是第二天所以我对以下内容:

    //open = string 11:00
    //closed= string 02:45
    $open = \DateTime::createFromFormat('H:i', $open);
    $closed = \DateTime::createFromFormat('H:i', $closed);
    if ($open > $closed) $closed->modify('+1 day');

现在我有2个正确的日期时间格式。现在我想设置从开放时间到关闭时间30分钟的时间间隔。我怎样才能做到这一点?我读过我可以这样添加

->add(new DateInterval('PT30M') b

它会添加到一天结束..但在这种情况下它会一直打开到第二天,所以我希望它能够填充到凌晨2:45

我该怎么做?

1 个答案:

答案 0 :(得分:1)

你走在正确的轨道上。以下是使用DateInterval('PT30M')

的方法
$strOpen = '11:00';
$strClose = '02:45';

$open = DateTime::createFromFormat('H:i', $strOpen);
$closed = DateTime::createFromFormat('H:i', $strClose);
if ($open > $closed) $closed->modify('+1 day');
// I display not only the time, but the day as well to show that it is
// incrementing to the next day. 
echo 'open:  ' . $open->format('D H:i') . "<br />\n";
while ($open < $closed) {
    $open->add(new DateInterval('PT30M'));
    // because incrementing on the half hour and our finish is on the 15 min,
    // the last is $open < $close in the while statement will be true but
    // this loop will generate a time after $closed so we do another check
    // now to eliminate that issue
    if ($open < $closed) {
        echo '+30min: ' . $open->format('D H:i') . "<br />\n";
    }
}
echo 'closed: ' . $closed->format('D H:i') . "<br />\n";