Round minute down to nearest quarter hour

Rob picture Rob · Mar 19, 2010 · Viewed 53.9k times · Source

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

Answer

Veger picture Veger · Mar 19, 2010
$seconds = time();
$rounded_seconds = round($seconds / (15 * 60)) * (15 * 60);

echo "Original: " . date('H:i', $seconds) . "\n";
echo "Rounded: " . date('H:i', $rounded_seconds) . "\n";

This example gets the current time and rounds it to the nearest quarter and prints both the original and the rounded time.

PS: If you want to round it down replace round() with floor().