Round minute down to nearest quarter hour

2019-01-03 15:25发布

I need to round times down to the nearest quarter hour in PHP. The times are being pulled from a MySQL database from a datetime column and formatted like 2010-03-18 10:50:00.

Example:

  • 10:50 needs to be 10:45
  • 1:12 needs to be 1:00
  • 3:28 needs to be 3:15
  • etc.

I'm assuming floor() is involved but not sure how to go about it.

Thanks

14条回答
放我归山
2楼-- · 2019-01-03 15:57

Simple solution:

$oldDate = "2010-03-18 10:50:00";
$date = date("Y-m-d H:i:s", floor(strtotime($oldDate) / 15 / 60) * 15 * 60);

You can change floor to ceil if you want to round up.

查看更多
ら.Afraid
3楼-- · 2019-01-03 16:00

Might help others. For any language.

roundedMinutes = yourRoundFun(Minutes / interval) * interval.

E.g. The interval could be 5 minutes , 10 minutes, 15 minutes, 30 minutes. Then rounded minutes can be reset to the respective date.

yourDateObj.setMinutes(0) 
yourDateObj.setMinutes(roundedMinutes)
查看更多
登录 后发表回答