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

Lyo*_*yon 19 php timestamp

假设我在PHP中有一个unix时间戳.如何将我的php时间戳舍入到最近的分钟?例如16:45:00而不是16:45:34?

谢谢你的帮助!:)

Yac*_*oby 53

如果时间戳是Unix风格的时间戳,那么简单

$rounded = round($time/60)*60;
Run Code Online (Sandbox Code Playgroud)

如果它是您指定的样式,您只需将其转换为Unix样式时间戳并返回

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

round()用作确保它舍入到x两者之间的值的简单方法x - 0.5 <= x < x + 0.5.如果你总是想要总是向下舍入(如所示)你可以使用floor()或模数函数

$rounded = floor($time/60)*60;
//or
$rounded = time() - time() % 60;
Run Code Online (Sandbox Code Playgroud)


Nic*_*ick 6

另一种选择是:

$t = time();
$t -= $t % 60;
echo $t;
Run Code Online (Sandbox Code Playgroud)

我已经读过,time()PHP 中的每次调用都必须通过堆栈一直回到操作系统.我不知道这是否已经在5.3+中改变了?上面的代码减少了对time()的调用...

基准代码:

$ 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";'
Run Code Online (Sandbox Code Playgroud)

有趣的是,超过10,000,000个itterations三个实际上同时执行;)