Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a total ammount of milliseconds (ie 70370) and I want to display it as minutes:seconds:milliseconds ie 00:00:0000.

How can I do this in PHP?

like image 281
designvoid Avatar asked Dec 02 '09 16:12

designvoid


3 Answers

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", $milliseconds / 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.
like image 74
nickf Avatar answered Nov 16 '22 15:11

nickf


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);
like image 22
soulmerge Avatar answered Nov 16 '22 15:11

soulmerge


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);
like image 4
jab11 Avatar answered Nov 16 '22 16:11

jab11