Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Youtube Data API V3 video duration format to standard time in PHP

I'm, getting this array from a youtube API request, but the duration format is very rare in my opinion. Why didn't they just throw seconds in there? In any case this is the array

[duration] => PT2M3S
[dimension] => 2d
[definition] => sd
[caption] => false

Is there a way to convert this duration to a "H:i:s" format in PHP?

Thanks in advance for your help

like image 357
user2915047 Avatar asked Nov 30 '22 02:11

user2915047


2 Answers

acidjazz has a great solution, but there is a typo where it displays the minutes. It should be $di->i for minutes, not $di->m. You can also remove the "public static" portion if you're not using it in an object, and I took out the sprintf().

Otherwise the function works as is:

function duration($ytDuration) {

    $di = new DateInterval($ytDuration);
    $string = '';

    if ($di->h > 0) {
      $string .= $di->h.':';
    }

    return $string.$di->i.':'.$di->s;
}

I would have added this as a comment to his answer, but there's the whole "You need 50 reputation to comment" BS that prevents me from sticking to the flow of this thread.

like image 59
James Avatar answered Dec 05 '22 17:12

James


In fact it is simple ISO8601 date. Split string with regexp like (\d+) to minutes and seconds. Then get integer part of division of minutes by 60 to get hours. Get remainder of that division to get minutes.

here is an example that should work though i didn't tested it

preg_match_all('/(\d+)/',$youtube_time,$parts);

$hours = floor($parts[0][0]/60);
$minutes = $parts[0][0]%60;
$seconds = $parts[0][1];
like image 27
Andrew Avatar answered Dec 05 '22 16:12

Andrew