我总共有毫秒的毫秒(即70370),我想显示为分钟:秒:毫秒:00:00:0000。

我该如何在PHP中执行此操作?

有帮助吗?

解决方案

不要属于使用日期函数的陷阱!您在这里拥有的是时间间隔,而不是日期。天真的方法是这样做这样的事情:

date("h:i:s.u", $mytime / 1000)

但是,由于日期函数用于(gasp!)日期,因此在这种情况下,它无法按照您想要的时间来处理时间 - 它在格式化日期/时间时需要考虑时区和日光节省等。

相反,您可能只想做一些简单的数学:

$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中格式化Miliseconds,您需要使用数学。

尝试此功能以显示您喜欢的毫秒数:

<?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
?>

资源

如手册中所述:

U微秒(添加到PHP 5.2.2中)示例:654321

我们有一个date()函数的'u'参数

例子:

if(($u/60) >= 60)
{
$u = mktime(0,($u / 360));
}
date('H:i:s',$u);

将毫秒转换为格式化时间

<?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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top