how do i convert PT2H34M25S to 2:34:25
I searched and used this code. I'm new to regex can someone explain this ? and help me with my issue
function covtime($youtube_time){
preg_match_all('/(\d+)/',$youtube_time,$parts);
$hours = floor($parts[0][0]/60);
$minutes = $parts[0][0]%60;
$seconds = $parts[0][1];
if($hours != 0)
return $hours.':'.$minutes.':'.$seconds;
else
return $minutes.':'.$seconds;
}
but this code only give me HH:MM
so dumb found the solution :
function covtime($youtube_time){
preg_match_all('/(\d+)/',$youtube_time,$parts);
$hours = $parts[0][0];
$minutes = $parts[0][1];
$seconds = $parts[0][2];
if($seconds != 0)
return $hours.':'.$minutes.':'.$seconds;
else
return $hours.':'.$minutes;
}
try this will give you duration by seconds
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 usingadd()
method. Then you can format the resulting date to obtain the required results:Demo
This is my solution, test completed!
I use two classes, 1 to call YouTube API, and one to convert the time. here it is simplified.
As you can see, YouTubeGet is a static class, but it does not have to be. YouTubeDateInterval however has to be an instance due to the way that DateInterval works (which is being extended).
usage is either about passing a iso 8601 date to YouTubeDateInterval.
or passing the YouTubeGet the api and video id key
Try the following function:
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" }