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!

Link to comment
Share on other sites

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');

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.