Php 将日期时间舍入到最近的四分之一小时
如何将DateTime对象舍入到最接近的四分之一小时Php 将日期时间舍入到最近的四分之一小时,php,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,依此类推。您可以提取分钟数,将其除以15,四舍五入,再乘以15。 差不多 // round the "minutes" $quarter = round(date('i', $yourdate) / 15) * 15; // get the new times
因此:2011-05-30 09:11:00将四舍五入为2011-05-30 09:15:00,2011-05-30 09:47:00将四舍五入为2011-05-30 09:45:00,依此类推。您可以提取分钟数,将其除以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));
如果四舍五入大于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);
这就是我在代码中的实现方式。可能有更优雅/高效的方法,但这似乎是可行的
// 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"));
}
用于任意舍入PHP日期时间的函数: