'PHP date increment every x minutes and loop until x times

I'm new in php.

I want to ask how to make increment loop date every x minus or x hours and repeat until x times.

Example :

  1. I have time : 2016-03-22T23:00:00
  2. I want to increment that time every 30 minutes
  3. And repet until 6 times.

and output will be :

  1. 2016-03-22T23:00:00
  2. 2016-03-22T23:30:00
  3. 2016-03-23T00:00:00
  4. 2016-03-23T00:30:00
  5. 2016-03-23T01:00:00
  6. 2016-03-23T01:30:00

My former code form other question in stackoverflow :

<?php
$startdate=strtotime("next Tuesday");
$enddate=strtotime("+1 weeks",$startdate); //16 weeks from the starting date
$currentdate=$startdate;

echo "<ol>";
while ($currentdate < $enddate): //loop through the dates
    echo "<li>",date('Y-m-d', $currentdate),"T";
    echo date('H:i:s', $currentdate);
    echo "</li>";

    $currentdate = strtotime("+30 minutes", $currentdate); //increment the current date
endwhile; // calculate date range
echo "<ol>";?>

On that code the loop stop until desire date. My problem is how to make increment in time until desire times..., for example 5 , 10, 10, 500 times loop? How to code that?



Solution 1:[1]

PHP's DateTime feature has the perfect option to do what you want:

// Set begin date
$begin = new DateTime('2016-03-17 23:00:00');

// Set end date
$end = new DateTime('2016-03-18 23:00:00');

// Set interval
$interval = new DateInterval('PT30M');

// Create daterange
$daterange = new DatePeriod($begin, $interval ,$end);

// Loop through range
foreach($daterange as $date){
    // Output date and time
    echo $date->format("Y-m-dTH:i:s") . "<br>";
}

Solution 2:[2]

Just use for-loop for this task:

<?php
$desiredtimes = 500; // desired times
$startdate=strtotime("next Tuesday");
$currentdate=$startdate;

echo "<ol>";
for ($i = 0; $i < $desiredtimes; $i++){ //loop desired times
    echo "<li>",date('Y-m-d', $currentdate),"T";
    echo date('H:i:s', $currentdate);
    echo "</li>";

    $currentdate = strtotime("+30 minutes", $currentdate); //increment the current date
} // calculate date range
echo "<ol>";?>

Solution 3:[3]

Use a DateTime object, then setup a loop that will iterate exactly 6 times.

After printing the current datetime, increase the datetime object by 30 minutes.

Code: (Demo)

$dt = new DateTime("2016-03-22T23:00:00");
for ($i = 0; $i < 6; ++$i, $dt->modify('+30 minutes')) {
    echo $dt->format("Y-m-d\TH:i:s") . "\n";
}

Output:

2016-03-22T23:00:00
2016-03-22T23:30:00
2016-03-23T00:00:00
2016-03-23T00:30:00
2016-03-23T01:00:00
2016-03-23T01:30:00

This was inspired by a more complex process that I scripted for CodeReview.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 alexander.polomodov
Solution 3 mickmackusa