Assuming I have a unix timestamp in开发者_StackOverflow中文版 PHP. How can I round my php timestamp to the nearest minute? E.g. 16:45:00 as opposed to 16:45:34?
Thanks for your help! :)
If the timestamp is a Unix style timestamp, simply
$rounded = round($time/60)*60;
If it is the style you indicated, you can simply convert it to a Unix style timestamp and back
$rounded = date('H:i:s', round(strtotime('16:45:34')/60)*60);
round()
is used as a simple way of ensuring it rounds to x
for values between x - 0.5 <= x < x + 0.5
. If you always wanted to always round down (like indicated) you could use floor()
or the modulo function
$rounded = floor($time/60)*60;
//or
$rounded = time() - time() % 60;
An alternative is this:
$t = time();
$t -= $t % 60;
echo $t;
I've read that each call to time()
in PHP had to go all the way through the stack back to the OS. I don't know if this has been changed in 5.3+ or not? The above code reduces the calls to time()...
Benchmark code:
$ php -r '$s = microtime(TRUE); for ($i = 0; $i < 10000000; $i++); $t = time(); $t -= $t %60; $e = microtime(TRUE); echo $e - $s . "\n\n";'
$ php -r '$s = microtime(TRUE); for ($i = 0; $i < 10000000; $i++); $t = time() - time() % 60; $e = microtime(TRUE); echo $e - $s . "\n\n";'
$ php -r '$s = microtime(TRUE); for ($i = 0; $i < 10000000; $i++); $t = floor(time() / 60) * 60; $e = microtime(TRUE); echo $e - $s . "\n\n";'
Interestingly, over 10,000,000 itterations all three actually do the same time ;)
Ah dam. Beat me to it :)
This was my solution also.
<?php
$round = ( round ( time() / 60 ) * 60 );
echo date('h:i:s A', $round );
?>
http://php.net/manual/en/function.time.php
Simply use the following :
$last_hour = date('Y-m-d H:00:00') // to last hour;
$last_minute = date('Y-m-d H:i:00') // to last minute;
I use it to delete old shopping carts with expiry date (+ 5 minutes grace) in my database :
// clean expired shopping carts
function shop_clean_carts($grace = 5) {
$expiry = date('Y-m-d H:i:00', strtotime("-$grace minutes"));
$q = "DELETE FROM `shop__cart`
WHERE `expiry` < '$expiry'
AND `expiry` IS NOT NULL
AND `fk_order_id` IS NULL";
$db->query($q);
return;
}
This is better to mySql NOW() because the query will be cached.
精彩评论