paganwinter
paganwinter

Reputation: 85

Rounding down UNIX time to lower hour in PHP

I have been trying in vain to round down the current time to the lower 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

Upvotes: 1

Views: 2151

Answers (4)

DShah
DShah

Reputation: 472

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

Upvotes: 0

igor
igor

Reputation: 2100

Just use date without printing the minutes, like:

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

Upvotes: 4

hsz
hsz

Reputation: 152236

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);

Upvotes: 2

drvdijk
drvdijk

Reputation: 5554

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);

Upvotes: 1

Related Questions