将日期时间修改为持续15分钟


Modify datetime to last 15 minutes

我有日期时间:

2014-08-05 13:27:00
2014-08-05 13:29:00 
2014-08-05 13:36:00 
2014-08-05 13:38:00

如何在将DateTime::modify()设置为的情况下对此进行修改

2014-08-05 13:15:00
2014-08-05 13:15:00 
2014-08-05 13:30:00 
2014-08-05 13:30:00

(因此,在最后15分钟被击倒。)

只需计算你需要减去多少分钟,就可以得到你想要的结果:

$dt = new DateTime('2014-08-05 13:27:00');
$min = $dt->format('i') % 15;
$dt->modify("-$min minutes");
echo $dt->format('Y-m-d H:i:s');

演示

当您请求它使用DateTime::modify()时,您可以这样做:

function roundToLastQuarterHour($date_string) {
    $date = new DateTime($date_string);
    // Remove any seconds, we don't need them
    $seconds = $date->format('s');
    $date->modify('-' . $seconds . ' seconds');
    // Store the original number of minutes on the datetime
    $original_minutes = $date->format('i');
    // Calculate how many minutes past the last quarter hour
    $remaining_minutes = $original_minutes - ($original_minutes - ($original_minutes % 15));
    // Modify the minutes, remove the number of minutes past the last quarter of an hour
    $date->modify('-' . $remaining_minutes . ' minutes');
    return $date;
}
roundToLastQuarterHour('2014-08-05 13:27:00')
// 2014-08-05 13:15:00
roundToLastQuarterHour('2014-08-05 13:29:00')
// 2014-08-05 13:15:00
roundToLastQuarterHour('2014-08-05 13:36:00')
// 2014-08-05 13:30:00
roundToLastQuarterHour('2014-08-05 13:38:00')
// 2014-08-05 13:30:00

这样做…

$adt = date("Y-m-d G:i:s",strtotime("2014-08-05 13:37:00")); // your desired time 
$min = date("i",strtotime("2014-08-05 13:37:00")); // taking the min out
// echo $adt;
if($min<15) $min =00; //changing the min value
elseif(15<$min && $min<30) $min =15;
elseif(30<$min && $min<45) $min =30;
elseif(45<$min && $min<=59) $min =45;
echo date("Y-m-d G:",strtotime($adt)).$min.date(":s",strtotime($adt)); //print or store it in a var

如果使用更多的时间值,也可以作为函数。。。