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
Your full function would be something like this...
For my system I wanted to add jobs which are scheduled to run every 5th minute on my server, and I want the same job to run in the next 5th minute block, then 15, 30, 60, 120, 240 minutes, 1 day and 2 days after, so that's what this function calculates
I wrote a function that does the trick to round time stamps to seconds or minutes.
I might not be the most performant way, but I think PHP doens't care about a few simple loops.
In your case, you just pass your MySQL datetime like this:
Returns: the closests rounded value (looks both up and down!)
The function:
You simple replace $entity by 's' if you want to round up or down to seconds and replace 15 by the amount of seconds or minutes you want to roud up or down to.
I needed a way to round down to the day, and cut off everything beyond that:
The strtotime gives me a timestamp for "now", which gmdate converts to ISO format (something like "2012-06-05T04:00:00+00:00"), then I use explode at the "T", giving me "2012-06-05" in the zeroth index of $explodedDate, which is then passed into date_create to get a date object.
Not sure if all of that is necessary, but it seems like a lot less work than going through and subtracting the seconds, minutes, hours etc.