我总共有毫秒(即 70370),我想将其显示为分钟:秒:毫秒,即 00:00:0000。
我怎样才能在 PHP 中做到这一点?
不要陷入为此使用日期函数的陷阱!您在这里拥有的是时间间隔,而不是日期。天真的方法是做这样的事情:
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.
如果您使用的是 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
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
?>
我相信 PHP 中没有用于格式化毫秒的内置函数,您需要使用数学。
将毫秒转换为格式化时间
<?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');
...
瞧,你完成了