Round DateTime到最接近的四分之一小时

时间:2011-06-02 10:00:24

标签: php

如何将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等等。

3 个答案:

答案 0 :(得分:5)

你可以提取分钟数除以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));

答案 1 :(得分: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);

答案 2 :(得分:0)

这是我在代码中执行此操作的方式。可能有更优雅/有效的方式,但这似乎有效。

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