将 php 时间戳舍入到最接近的分钟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2364625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Round php timestamp to the nearest minute
提问by Lyon
Assuming I have a unix timestamp in PHP. How can I round my php timestamp to the nearest minute? E.g. 16:45:00 as opposed to 16:45:34?
假设我在 PHP 中有一个 unix 时间戳。如何将我的 php 时间戳四舍五入到最接近的分钟?例如 16:45:00 而不是 16:45:34?
Thanks for your help! :)
谢谢你的帮助!:)
回答by Yacoby
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 xfor 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
round()用作确保它舍入到x之间的值的简单方法x - 0.5 <= x < x + 0.5。如果您总是想始终向下舍入(如所示),您可以使用floor()或模函数
$rounded = floor($time/60)*60;
//or
$rounded = time() - time() % 60;
回答by Nick
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()...
我读过,time()在 PHP中的每个调用都必须通过堆栈一直返回到操作系统。我不知道这是否在 5.3+ 中有所改变?上面的代码减少了对 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 次迭代实际上是同时进行的 ;)
回答by Layke
Ah dam. Beat me to it :)
啊大坝。打败我:)
This was my solution also.
这也是我的解决方案。
<?php
$round = ( round ( time() / 60 ) * 60 );
echo date('h:i:s A', $round );
?>

