What would be a good solution to round a timestamp to the hour?
For example, after using date('d.m.y h:m', time())
, I get '02.08.11 7:07'... Now, from this, I'd like to have the timestamp for 7:00.
How can I achieve that?
After seeing Greg Miller's "Time Programming Fundamentals" talk about Google's cctz C++ library, I am dissatisfied with my previous answer.
Handling time is a very complex topic (even when discounting relativistic effects). We have to honor things like timezones with uneven offsets, daylight saving time, time jumps due to legislation changes or leap seconds and probably many more quirks. While many of these have only a local effect in time and space, users of our programs can still be unlucky enough to get affected.
It is probably best to rely on underlying functions like in holodoc's answer to handle the quirks of timezone management.
When I remember correctly the timestamp started at exactly 0:00 1.1.1970 so it should suffice to divide it by 3600 (floating) then round/floor/ceil and multiply by 3600 (integer). The division must be floating point for round/ceil to work.
Sample of rounding:
round($timestamp/3600)*3600
7:20 -> 7:00
7:40 -> 8:00
Sample of flooring:
floor($timestamp/3600)*3600
7:20 -> 7:00
7:40 -> 7:00
Sample of ceiling:
ceil($timestamp/3600)*3600
7:20 -> 8:00
7:40 -> 8:00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With