【发布时间】:2010-12-22 11:25:40
【问题描述】:
我的总毫秒数(即 70370),我想将其显示为分钟:秒:毫秒,即 00:00:0000。
我如何在 PHP 中做到这一点?
【问题讨论】:
标签: php date time-format
我的总毫秒数(即 70370),我想将其显示为分钟:秒:毫秒,即 00:00:0000。
我如何在 PHP 中做到这一点?
【问题讨论】:
标签: php date time-format
不要陷入为此使用日期函数的陷阱!您在这里拥有的是时间间隔,而不是日期。天真的方法是这样做:
date("H:i:s.u", $milliseconds / 1000)
但是由于 date 函数用于(喘气!)日期,它不会按照您在这种情况下想要的方式处理时间 - 在格式化日期时需要考虑时区和夏令时等/时间。
相反,您可能只想做一些简单的数学运算:
$input = 70135;
$uSec = $input % 1000;
$input = floor($input / 1000);
$seconds = $input % 60;
$input = floor($input / 60);
$minutes = $input % 60;
$input = floor($input / 60);
// and so on, for as long as you require.
【讨论】:
gmdate()。
如果您使用的是 PHP 5.3,您可以使用 DateInterval 对象:
list($seconds, $millis) = explode('.', $milliseconds / 1000);
$range = new DateInterval("PT{$seconds}S");
echo $range->format('%H:%I:%S') . ':' . str_pad($millis, 3, '0', STR_PAD_LEFT);
【讨论】:
既然可以使用数学,为什么还要麻烦date() 和格式化?
如果$ms 是您的毫秒数
echo floor($ms/60000).':'.floor(($ms%60000)/1000).':'.str_pad(floor($ms%1000),3,'0', STR_PAD_LEFT);
【讨论】:
我相信 PHP 中没有用于格式化毫秒的内置函数,您需要使用数学。
【讨论】:
试试这个函数,以你喜欢的方式显示毫秒数:
<?php
function udate($format, $utimestamp = null)
{
if (is_null($utimestamp)) {
$utimestamp = microtime(true);
}
$timestamp = floor($utimestamp);
$milliseconds = round(($utimestamp - $timestamp) * 1000000);
return date(preg_replace('`(?<!\\\\)u`', sprintf("%06u", $milliseconds), $format), $timestamp);
}
echo udate('H:i:s.u'); // 19:40:56.78128
echo udate('H:i:s.u', 654532123.04546); // 16:28:43.045460
?>
【讨论】:
preg_replace 在做什么。看起来很奇怪。
sprintf("%06u", $milliseconds)之类的东西,否则5毫秒看起来像0.5
将毫秒转换为格式化时间
<?php
/* Write your PHP code here */
$input = 7013512333;
$uSec = $input % 1000;
$input = floor($input / 1000);
$seconds = $input % 60;
$input = floor($input / 60);
$minutes = $input % 60;
$input = floor($input / 60);
$hour = $input ;
echo sprintf('%02d %02d %02d %03d', $hour, $minutes, $seconds, $uSec);
?>
在这里查看演示: https://www.phprun.org/qCbY2n
【讨论】:
如手册所述:
u 微秒(在 PHP 5.2.2 中添加) 示例:654321
我们有一个 date() 函数的 'u' 参数
例子:
if(($u/60) >= 60)
{
$u = mktime(0,($u / 360));
}
date('H:i:s',$u);
【讨论】:
不,您可以使用 CarbonInterval:
use Carbon\CarbonInterval;
...
$actualDrivingTimeString = CarbonInterval::seconds($milliseconds/1000)
->cascade()->format('%H:%I:%S');
...
瞧,你就完成了
【讨论】: