开发者

Rounding PHP timestamp

What would be a good soluti开发者_如何学Con 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?


Update

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.

TL;DR

It is probably best to rely on underlying functions like in holodoc's answer to handle the quirks of timezone management.

Old Answer

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


Ever thought about removing the minutes? :)

echo date('d.m.y h:00', time());

If you need the timestamp of the beginning minute just alter your data argument a bit and use strtotime.

echo strtotime(date('d.m.Y H:00:00', time()));


Capture the hour and the minute into 2 different variables. If the minutes is >= 30 then add one to the hour.

Not the most elegant solution, but it works. :)


Simplest solution:

date('d.m.y h', time());

It's very uncommon to see any sort of timestamps where the hour is rounded up. If the timestamp says 7:00 - it means it happened in the 7th hour, anytime. If you start rounding up timestamps people will interpret it as having occurred anytime in the 8th hour... which can lead to confusion.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜