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
It's an old question but having recently implemented myself I'll share my solution:-
Here's a function I'm currently using:
Hope it helps someone :)
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()
withfloor()
.Lately I like tackling a problem the TDD/unit testing way. I am not programming much PHP anymore lately, but this is what I came up with. To be honest I actually looked at the code examples here, and picked the one I thought was already correct. Next I wanted to verify this by unit testing using the tests you provided above.
class TimeTest
class Time
Running Test
To round nearest quarter hour use below code
01:08 become 01:15