【问题标题】:Fill Out The Gaps Between Two Times With PHP用 PHP 填补两次之间的空白
【发布时间】:2011-08-18 18:41:27
【问题描述】:

我必须编写一个应该在两次之间开始和结束的循环。我知道有很多方法可以给这只猫剥皮,但我希望看到真正的程序员处理这个功能。

例如,基本上我有星期三,下午 6:00 开门,晚上 10:30 关门。

我正在寻找一个循环,它会给我一个表格,其中包含这两者之间的所有时间,间隔为 15 分钟。

所以,我基本上想建立一个单列表,其中每一行都是

6:00pm
6:15pm
7:15pm

等等……

我为这个函数提供的两个变量是打开时间和关闭时间。 现在不要指责我“为我写代码”发帖。我很乐意应要求为您提供我的破解解决方案,我只是想看看有实际经验的人如何创建此功能。

谢谢:)

【问题讨论】:

    标签: php loops


    【解决方案1】:

    PHP 5.3 专门为此目的引入了一个类,DatePeriod

    $start    = new DateTime("6:00pm");
    $end      = new DateTime("10:30pm");
    $interval = new DateInterval('PT15M');
    $period   = new DatePeriod($start, $interval, $end);
    
    foreach ($period as $time) {
        echo $time->format('g:ia'), PHP_EOL;
    }
    
    echo $end->format('g:ia'); // end time is not part of the period
    

    【讨论】:

    • @Gerry,请注意在提到星期三之后的“例如”。适当地更改开始/结束日期/时间是微不足道的。
    • 我确实注意到了,我只是在开玩笑。
    • @Gerry,有时很难说……这里的人可以这么挑剔! :-)
    • 嘿,是的,无论您在哪一天使用,输出都是相同的。但我听到了。 :)
    【解决方案2】:
    $start = new DateTime("2011-08-18 18:00:00");
    $end = new DateTime("2011-08-18 22:30:00");
    $current = clone $start;
    while ($current <= $end) {
        echo $current->format("g:ia"), "\n";
        $current->modify("+15 minutes");
    }
    

    在键盘上试用:http://codepad.org/JwBDOQQE

    【讨论】:

    • 这是一件美丽的事情。谢谢 :)(我还要再等 6 分钟才能将您标记为正确,但是,它来了)
    • +1 - 虽然 start 变量和 clone 不是多余的吗? codepad.org/7LgqD2Mx
    • 另外你的日期是星期四,而问题是星期三。 ;D
    【解决方案3】:
    $start = strtotime('2011-08-11 18:00:00');
    
    for ($i = 0; $i < 20; $i++) {
       echo date('g:ia', $start + ($i * (15 * 60))), '<br>';
    }
    

    【讨论】:

    • 我看到你给出了可爱的答案(不是这个)为什么是 20 个?它是从哪里来的?
    • 只是一些随机的结束值。在这种情况下,它将输出 20 :15 分钟的间隔。
    • 但未完成请求
    【解决方案4】:

    只要当前时间低于结束时间,我会使用 DateTime 函数和 increase the time by 15 minutes 每次循环。

    编辑:正如 user576875 发布的那样

    【讨论】:

      【解决方案5】:
      $start_date = '2019-07-30 08:00:00';
      $end_date = '2019-09-31 08:00:00';
      while (strtotime($start_date) <= strtotime($end_date)) {
          echo "$start_date<br>";
      
      
          $start_date = date ("Y-m-d H:i:s", strtotime("+1 hours", strtotime($start_date)));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-13
        • 1970-01-01
        • 2019-08-14
        • 1970-01-01
        • 2022-11-30
        • 1970-01-01
        • 2015-08-19
        相关资源
        最近更新 更多