2017-06-13 36 views
0

我在PHP已经两个日期倍:PHP:环两个日期时间和打印分钟的差别

2017-06-14 13:00:00 
2017-06-30 20:00:00 

我想打印在循环每30分钟的时间,如下所示:

2017-06-14 13:00:00 
2017-06-14 13:30:00 
2017-06-14 14:00:00 
2017-06-14 14:30:00 
2017-06-14 15:00:00 
2017-06-14 15:30:00 
2017-06-14 16:00:00 
2017-06-14 16:30:00 
2017-06-14 17:00:00 
2017-06-14 17:30:00 
2017-06-14 18:00:00 
2017-06-14 18:30:00 
2017-06-14 19:00:00 
2017-06-14 19:30:00 
2017-06-14 20:00:00 

截至上次日期为6月30日。我正在使用while循环并打印时间差。请在下面找到我的代码。

$start_date = date("Y-m-d H:i:s", strtotime($_REQUEST["fromdate"]." ".$_REQUEST["fromtime"])); 
$end_date = date("Y-m-d H:i:s", strtotime($_REQUEST["todate"]." ".$_REQUEST["totime"])); 
while(strtotime($start_date) < strtotime($end_date)){ 
    $start_date = date("Y-m-d H:i:s", strtotime("+30 minutes", strtotime($start_date))); 
} 

我得到一天的所有时间,不管从时间到时间。我只需要从下午1点到8点的时间。任何帮助将不胜感激。在此先感谢

回答

0

尝试这样的:

$start = new DateTime('2017-06-14 13:00:00'); 
$end = new DateTime('2017-06-30 20:00:00'); 
$startHour = $start->format('H'); 
$endHour = $end->format('H'); 

while ($start <= $end){ 
    $startDay = clone $start; 
    $startDay->setTime($startHour, 0, 0); 
    $endDay = clone $start; 
    $endDay->setTime($endHour, 0, 0); 

    if ($start >= $startDay && $start <= $endDay){ 
     echo $start->format('Y-m-d H:i:s') . '<br />'; 
    } 
    $start->modify('+30 minutes'); 
} 
+0

的日期和时间是不固定的,将是动态的,所以我不能设置$ startDay->时刻设定(13,0,0); –

+0

我改变了我的答案 –

+0

非常感谢兄弟 –