Jump to content

[SOLVED] Round Timestamp to Nearest 15 Minutes


mister5317

Recommended Posts

I have timestamps in a database that are from the creation time of the records. These timestamps are something like 2009-06-29 08:54:32.

 

In this case, I would like to round this timestamp to the nearest 15 minute increment (00:00, 00:15, 00:30, or 00:45) so the end result for 2009-06-29 08:54:32 would be 2009-06-29 09:00:00.

 

If the time stamp was 2009-06-29 09:07:17, then the end result would still be 2009-06-29 09:00:00.

 

Another option, if possible, would be to always round up. Maybe have an argument in the function to round to nearest or to round up/down?

 

Can someone help me build a function to do this? It would be greatly appreciated!

 

Thank you!

I think I have figured it out!

 

<?php

function roundTime($timestamp, $precision = 15) {
  $timestamp = strtotime($timestamp);
  $precision = 60 * $precision;
  return date('Y-m-d H:i:s', round($timestamp / $precision) * $precision);
}

// 2009-06-29 10:45:00
echo roundTime('2009-06-29 10:48:13');

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.