Convert youtube Api v3 video duration in php Convert youtube Api v3 video duration in php php php

Convert youtube Api v3 video duration in php


Using DateTime class

You could use PHP's DateTime class to achieve this. This solution is much simpler, and will work even if the format of the quantities in the string are in different order. A regex solution will (most likely) break in such cases.

In PHP, PT2H34M25S is a valid date period string, and is understood by the DateTime parser. We then make use of this fact, and just add it to the Unix epoch using add() method. Then you can format the resulting date to obtain the required results:

function covtime($youtube_time){    if($youtube_time) {        $start = new DateTime('@0'); // Unix epoch        $start->add(new DateInterval($youtube_time));        $youtube_time = $start->format('H:i:s');    }        return $youtube_time;}   echo covtime('PT2H34M25S');

Demo


Both Amal's and Pferate's solutions are great!However, Amal solution keep giving me 1Hr extra. Below is my solution which is same with Amal but difference approach and this work for me.

$date = new DateTime('1970-01-01');$date->add(new DateInterval('PT2H34M25S'));echo $date->format('H:i:s')

datetime->add() reference


Here's my solution which handles missing H, M or S (test a video with a reported length of 1:00:01 and you'll see the problem with other answers). Seconds alone are presented as 0:01, but if you want to change that just change the last else to elseif($M>0) and add an else for seconds e.g. else { return ":$S" }

// convert youtube v3 api duration e.g. PT1M3S to HH:MM:SS// updated to handle videos days long e.g. P1DT1M3Sfunction covtime($yt){    $yt=str_replace(['P','T'],'',$yt);    foreach(['D','H','M','S'] as $a){        $pos=strpos($yt,$a);        if($pos!==false) ${$a}=substr($yt,0,$pos); else { ${$a}=0; continue; }        $yt=substr($yt,$pos+1);    }    if($D>0){        $M=str_pad($M,2,'0',STR_PAD_LEFT);        $S=str_pad($S,2,'0',STR_PAD_LEFT);        return ($H+(24*$D)).":$M:$S"; // add days to hours    } elseif($H>0){        $M=str_pad($M,2,'0',STR_PAD_LEFT);        $S=str_pad($S,2,'0',STR_PAD_LEFT);        return "$H:$M:$S";    } else {        $S=str_pad($S,2,'0',STR_PAD_LEFT);        return "$M:$S";    }}