使用php使用给定的持续时间获取两个时间之间的时间间隔


Get time interval between two time using php with given duraion using php?

我有开始时间和结束时间在php。如果我指定duration,它应该显示所有的时间间隔。
Startime = 2014-07-28 07:00:00
End Time = 2014-07-28 11:00:00
duration = 30 min

我需要输出开始和结束时间相差30分钟。

输出如下所示:

07:00, 07:30, 08:00, 08:30 .....10:00, 10:30, 11:00

try

$s = strtotime("2014-07-28 07:00:00");
$e = strtotime("2014-07-28 11:00:00");
while($s != $e) {
 $s = strtotime('+30 minutes', $s);
 echo date('H:i', $s);
}

输出:- 07:30 08:00 08:30 09:00 09:30 10:00 10:30 11:00

用于逗号分隔:-

while($s != $e) {
  $s = strtotime('+30 minutes', $s);
  $arr[] = date('H:i', $s);
}
echo implode(',', $arr);

输出:07:30时,喂饲,塔利班),上午9点,09:30,10点,十点半了,11点

使用DatePeriod类:

$start = new DateTime('2014-07-28 07:00:00');
$end = new DateTime('2014-07-28 11:00:00');
$interval = new DateInterval('PT30M');
$period = new DatePeriod($start, $interval, $end);
foreach($period as $time) {
    echo $time->format('Y-m-d H:i:s') . PHP_EOL;
}
输出:

2014-07-28 07:00:00
2014-07-28 07:30:00
2014-07-28 08:00:00
2014-07-28 08:30:00
2014-07-28 09:00:00
2014-07-28 09:30:00
2014-07-28 10:00:00
2014-07-28 10:30:00

你可以试试

$start = "2014-07-28 07:00:00";
$end = "2014-07-28 11:00:00";
$start_time = strtotime($start);
$end_time = strtotime($end);
$time_diff = 30 * 60;
for($i=$start_time; $i<=$end_time; $i+=$time_diff)
{
    echo date("H:i", $i).", ";
}

参见WORKING DEMO