简体   繁体   中英

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?

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>";
}

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>";?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM