2010-03-02 96 views
17

假设我在PHP中有一个unix时间戳。我怎样才能将我的php时间戳四舍五入到最接近的分钟?例如。 16:45:00而不是16:45:34?圆形PHP时间戳到最近的分钟

感谢您的帮助! :)

+0

16:45:00仍有几秒钟...我想你的意思是你想轮到下一个最接近的分钟,而不是删除秒。 – Layke 2010-03-02 16:12:47

+0

我刚刚安装了PHP,因此我可以为您提供执行此操作的代码。我不想猜测因为我讨厌时间()。如果没有其他人,我会在10分钟内回答。 – Layke 2010-03-02 16:16:46

+4

@Laykes http://codepad.org/适合做快速代码检查 – Yacoby 2010-03-02 16:23:24

回答

49

如果时间戳是一个Unix风格的时间戳,只需

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

如果您指定的样式,你可以简单地将其转换为Unix类型时间戳和背部

$rounded = date('H:i:s', round(strtotime('16:45:34')/60)*60); 

使用round()作为确保其值为x的简单方法,其值在x - 0.5 <= x < x + 0.5之间。如果你一直想永远本轮下跌(如所示),你可以使用floor()或模函数

$rounded = floor($time/60)*60; 
//or 
$rounded = time() - time() % 60; 
+0

Yacoby,谢谢你的全面解释!现在你已经提到过了,round()是我喜欢的函数。在我的应用程序中更有意义。 :) – Lyon 2010-03-02 16:28:33

2

阿坝。打我吧:)

这也是我的解决方案。

<?php 
$round = (round (time()/60) * 60); 

echo date('h:i:s A', $round); 
?> 

http://php.net/manual/en/function.time.php

+0

呵呵,我真的很感谢你的帮助!谢谢 :) – Lyon 2010-03-02 16:26:31

6

另一种方法是这样的:

$t = time(); 
$t -= $t % 60; 
echo $t; 

我读过,在PHP每次调用time()只好一路通过堆栈回OS。我不知道5.3以上版本是否已经改变了?上面的代码减少了时间()的调用...

基准代码:

$ 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";' 

有趣的是,超过10,000,000 itterations所有三个实际做的同时;)

相关问题