【问题标题】:PHP date increment every x minutes and loop until x timesPHP日期每x分钟递增一次并循环直到x次
【发布时间】:2022-04-09 10:22:10
【问题描述】:

我是 php 新手。

我想问如何使每 x 减去或 x 小时递增循环日期并重复直到 x 次。

例子:

  1. 我有时间:2016-03-22T23:00:00
  2. 我想每 30 分钟增加一次时间
  3. 并重复直到 6 次。

输出将是:

  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

我以前的代码在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>";?>

在该代码上,循环停止直到所需日期。 我的问题是如何在需要的时间之前增加时间...,例如 5 、 10、 10、 500 次循环? 如何编码?

【问题讨论】:

    标签: php date


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      只需使用 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>";?>
      

      【讨论】:

        【解决方案3】:

        使用一个 DateTime 对象,然后设置一个将精确迭代 6 次的循环。

        打印当前日期时间后,将日期时间对象增加 30 分钟。

        代码:(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";
        }
        

        输出:

        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
        

        这是受我为 CodeReview 编写的一个更复杂的过程所启发的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-11-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多