【问题标题】:Round DateTime to closest quarter hour将 DateTime 舍入到最接近的一刻钟
【发布时间】:2011-06-02 10:00:23
【问题描述】:

如何将 DateTime 对象舍入到最接近的一刻钟?

因此:2011-05-30 09:11:00 将四舍五入为 2011-05-30 09:15:00,2011-05-30 09:47:00 将四舍五入为 2011-05-30 09 :45:00 等等。

【问题讨论】:

标签: php


【解决方案1】:

您可以提取分钟数除以 15,四舍五入再乘以 15。 类似的东西

// round the "minutes"
$quarter = round(date('i', $yourdate) / 15) * 15;
// get the new timestamp
$roundeddate = mktime(date("H",$yourdate), $quarter, date("s",$yourdate), date("n",$yourdate), date("j",$yourdate), date("Y",$yourdate));

【讨论】:

    【解决方案2】:

    如果四舍五入大于 57,这也会产生问题。

    试试这个

    $current_date_time = '2014-04-14 00:58:01' ;
    
    $current_date_time = round(strtotime($current_date_time) / (15 * 60)) * (15 * 60);
    
    echo date('Y-m-d H:i:s', $current_date_time);
    

    【讨论】:

      【解决方案3】:

      这就是我在代码中的做法。可能有更优雅/更有效的方法,但这似乎有效。

       // remove seconds from the datetime (we add them back later)
          $seconds = $preset_date->format("s");
          $preset_date->sub(new DateInterval("PT". $seconds ."S"));
      
          // grab the minutes
          $minutes = $preset_date->format("i");
      
          // add in the seconds as a fraction of a minute
          $minutes = $minutes + ($seconds/60);
      
          // get the mod of the minutes
          $minutes = $minutes % 15;
      
          // if the mod is greater than half way then
          // add enough minutes to make it to the next quarter hour
          if($minutes >= 7.5){
              // round up
              $diff = 15 - $minutes;
              $preset_date->add(new DateInterval("PT".$diff."M"));
          }else{
              // we are less than halfway so round down to previous quarter
              $preset_date->sub(new DateInterval("PT".$minutes."M"));
          }
      

      【讨论】:

        猜你喜欢
        • 2011-01-29
        • 2016-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-15
        • 2013-11-17
        相关资源
        最近更新 更多