简体   繁体   English

将 php 时间戳舍入到最接近的分钟

[英]Round php timestamp to the nearest minute

Assuming I have a unix timestamp in PHP.假设我在 PHP 中有一个 unix 时间戳。 How can I round my php timestamp to the nearest minute?如何将我的 php 时间戳四舍五入到最接近的分钟? Eg 16:45:00 as opposed to 16:45:34?例如 16:45:00 而不是 16:45:34?

Thanks for your help!谢谢你的帮助! :) :)

If the timestamp is a Unix style timestamp, simply如果时间戳是 Unix 风格的时间戳,只需

$rounded = round($time/60)*60;

If it is the style you indicated, you can simply convert it to a Unix style timestamp and back如果它是您指定的样式,您可以简单地将其转换为 Unix 样式的时间戳并返回

$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 . round()用作一种简单的方法,可确保将x - 0.5 <= x < x + 0.5之间的值round()x If you always wanted to always round down (like indicated) you could use floor() or the modulo function如果您总是想始终向下舍入(如所示),您可以使用floor()或模函数

$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.我读过每次在 PHP 中调用time()都必须通过堆栈返回操作系统。 I don't know if this has been changed in 5.3+ or not?我不知道这是否在 5.3+ 中有所改变? The above code reduces the calls to time()...上面的代码减少了对 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 ;)有趣的是,超过 10,000,000 次迭代实际上是同时进行的 ;)

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 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 :我用它来删除我的数据库中具有到期日期(+ 5 分钟宽限期)的旧购物车:

// 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.这对 mySql NOW() 更好,因为查询将被缓存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM