简体   繁体   English

PHP日期每x分钟递增一次并循环直到x次

[英]PHP date increment every x minutes and loop until x times

I'm new in php.我是 php 新手。

I want to ask how to make increment loop date every x minus or x hours and repeat until x times.我想问一下如何使每 x 减或 x 小时递增循环日期并重复直到 x 次。

Example :示例:

  1. I have time : 2016-03-22T23:00:00我有时间:2016-03-22T23:00:00
  2. I want to increment that time every 30 minutes我想每 30 分钟增加一次该时间
  3. And repet until 6 times.并重复至 6 次。

and output will be :和输出将是:

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

My former code form other question in stackoverflow :我以前的代码在 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?我的问题是如何增加时间直到需要的时间......,例如 5 , 10, 10, 500 次循环? How to code that?如何编码?

PHP's DateTime feature has the perfect option to do what you want: PHP 的DateTime功能有一个完美的选择来做你想做的事:

// 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:只需为此任务使用 for 循环:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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