How can I convert a PT4M4S
format like from YouTube API format to a viewable format like 4:04
... and maybe for interest additional PT1H4M4S
to 1:04:04
both with the beginning zero by the four.
Asked
Active
Viewed 315 times
2 Answers
1
Convert duration into seconds with function below (extracted from this SO thread) :
function ISO8601ToSeconds($ISO8601) {
$interval = new \DateInterval($ISO8601); return ($interval->d * 24 * 60 * 60) + ($interval->h * 60 * 60) + ($interval->i * 60) + ($interval->s); }
Format the time in seconds to fit your needs :
gmdate("H:i:s", ISO8601ToSeconds('PT4M4S'));

PHPnoob
- 586
- 3
- 7
0
This should work for you.
Disclaimer: This hasn't been tested so I don't know if it works
<?php
$str = 'PT1H4M4S';
$str = substr($str, 2); //Returns 4M4S
$timeArray = str_split($string, 2); //Returns { '4M', '4S' }
$formattedTime = '';
foreach ($timeArray as $time) {
switch (substr($time, 0)) //Looking at first value
{
case 'H':
$formattedTime .= substr($time, 1); //Returns 4
break;
case 'M':
$formattedTime .= str_pad(substr($time, 1), 2, '0', STR_PAD_LEFT); //Returns 04
break;
case 'S':
$formattedTime .= str_pad(substr($time, 1), 2, '0', STR_PAD_LEFT); //Returns 04
break;
}
$formattedTime .= ':';
}
$formattedTime .= substr($time, -1); //Removes last ':'
echo $formattedTime;
?>

Haley Mueller
- 487
- 4
- 16