Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding PHP timestamp

Tags:

date

php

time

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?

like image 960
luqita Avatar asked Dec 02 '22 01:12

luqita


1 Answers

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
like image 150
Nobody moving away from SE Avatar answered Dec 26 '22 21:12

Nobody moving away from SE