我有日期时间:
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分钟的标记处......)
答案 0 :(得分:2)
只需计算你需要减去多少分钟,就可以得到你想要的结果:
$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');
答案 1 :(得分:1)
当您要求它使用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
答案 2 :(得分:0)
这样做......
$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
如果使用更多时间值,也可以作为函数...