mohamma shoaib nagori
mohamma shoaib nagori

Reputation: 21

PHP: loop two date times and print the difference in minutes

I've two date times in PHP as:

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

I want to print the time of every 30 minutes in loop as given below:

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

Up to last date 30th June. I am using while loop and printing the time difference. Please find below my code.

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

I am getting all the times of a day irrespective of from time and to time. I want time only from 1 PM to 8 PM. Any help will be appreciated. Thanks in advance

Upvotes: 0

Views: 68

Answers (1)

Try like this:

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

Upvotes: 1

Related Questions