Skip to content

Instantly share code, notes, and snippets.

@bcls
Last active September 24, 2024 16:34
Show Gist options
  • Save bcls/be86fd21a933bb748ea28fcd0f4f33fc to your computer and use it in GitHub Desktop.
Save bcls/be86fd21a933bb748ea28fcd0f4f33fc to your computer and use it in GitHub Desktop.
convert milliseconds to formatted time #php
/**
* Converts milliseconds to formatted time or seconds.
* @param int [$ms] The length of the media asset in milliseconds
* @param bool [$seconds] Whether to return only seconds
* @return mixed The formatted length or total seconds of the media asset
*/
function convertTime($ms, $seconds = false)
{
$total_seconds = ($ms / 1000);
if($seconds)
{
return $total_seconds;
} else {
$time = '';
$value = array(
'hours' => 0,
'minutes' => 0,
'seconds' => 0
);
if($total_seconds >= 3600)
{
$value['hours'] = floor($total_seconds / 3600);
$total_seconds = $total_seconds % 3600;
$time .= $value['hours'] . ':';
}
if($total_seconds >= 60)
{
$value['minutes'] = floor($total_seconds / 60);
$total_seconds = $total_seconds % 60;
$time .= $value['minutes'] . ':';
} else {
$time .= '0:';
}
$value['seconds'] = floor($total_seconds);
if($value['seconds'] < 10)
{
$value['seconds'] = '0' . $value['seconds'];
}
$time .= $value['seconds'];
return $time;
}
}
@threepointnz
Copy link

I forked this gist to fix a display error. I wanted to display 4 hours. It displayed as: 4:0:00. It should be 4:00:00.

Line 38, I added an extra 0.

@mrwweb
Copy link

mrwweb commented Sep 24, 2024

In recent versions of PHP:

Implicit conversion from float XXXX.XXX to int loses precision in …

I resolved this by changing $total_seconds = ($ms / 1000); to $total_seconds = floor($ms / 1000);.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment