How do I format an amount of milliseconds into minutes:seconds:milliseconds in PHP?

你说的曾经没有我的故事 提交于 2019-11-28 23:29:58

Don't fall into the trap of using date functions for this! What you have here is a time interval, not a date. The naive approach is to do something like this:

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

but because the date function is used for (gasp!) dates, it doesn't handle time the way you would want it to in this situation - it takes timezones and daylight savings, etc, into account when formatting a date/time.

Instead, you will probably just want to do some simple maths:

$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.

If you are using PHP 5.3 you can make use of the DateInterval object:

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);
jab11

why bother with date() and formatting when you can just use math ? if $ms is your number of milliseconds

echo floor($ms/60000).':'.floor(($ms%60000)/1000).':'.str_pad(floor($ms%1000),3,'0', STR_PAD_LEFT);

I believe there's no built-in function for formatting miliseconds in PHP, you'll need to use maths.

Try this function to display amount of milliseconds the way you like:

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

Source

As mentioned in the manual:

u Microseconds (added in PHP 5.2.2) Example: 654321

We have a 'u' parameter for the date() function

Example:

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

convert milliseconds to formatted time

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

check demo here : https://www.phprun.org/qCbY2n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!