views:

58

answers:

3

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

A: 

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);
drvdijk
That wouldn't take into account leap-seconds...
ircmaxell
No luck, look at the example below:16-08-2010 19:19 becomes 16-08-2010 18:30
Paganwinter
+1  A: 

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);
hsz
I had initially done that, and it does work. But it seemed like a hack :PWanted to do it the 'proper' way...
Paganwinter
This is a proper way :)
Tomasz Struczyński
Why not use `date('d m Y H:00');`? It's the same thing, but a little cleaner...
ircmaxell
@This is a proper way :)Thats good enuff for me :PThink I'll stick to just that! Wasted too much time on such a small thing already. Thanks everyone...
Paganwinter
+2  A: 

Just use date without printing the minutes, like:

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