开发者

Rounding down UNIX time to lower hour in PHP

开发者 https://www.devze.com 2023-01-12 05:54 出处:网络
I have been trying in vain to round down the current time to the lowe开发者_如何学Pythonr hour in PHP.

I have been trying in vain to round down the current time to the lowe开发者_如何学Pythonr hour in PHP.

Here's what I want to do: 1. Take the current time: $time_now = time(); 2. Round it down to the closest hour: $time_now = $time_now - ($time_now % 3600); 3. Print it using the function date: print date('d m Y H:i', $time_test);

But what seems to be happening is that the printed time is what I want + 30 minutes. e.g: If current time is 19:03, I get an output of 18:30 instead of 19:00 and if the time is 19:34, I get an output of 19:30 instead of 19:00

This driving me crazy! X( What seems to be wrong in this code?! Something to do with the timezone perhaps? My system time is GMT +5:30


Just use date without printing the minutes, like:

print date('d m Y H') . ':00';


Can't you do just:

$now = time();
echo date('d m Y H', $now) . ':00';

// or just

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

?

It will print you current hour and fake minutes.

If you want to use that timestamp you can convert it with strtotime function.

$date = date('d m Y H') . ':00';
$timestamp = strtotime($date);


The function you're looking for is floor. The following works as you would like I think:

$time_now = floor(time() / 3600) * 3600;
print date('d-m-Y H:i', $time_now);


$d = strtotime($date);
$rounded = intval($d / 3600) * 3600;
$formatted_rounded = date('Y-m-d H:i:s', $rounded)
0

精彩评论

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