I am retrieving date from the url `
https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics,status
&videoSyndicated=true
&type=video
&id=CRvoJEqrYTY
&key=AIzaSyD68YEP1N9J0-umFWuzMV3NEN3T5VBvoHo`
as PT1H8M21S
. How to convert it into hh:mm:ss
using php
The string 'PT1H8M21S'
it's not a Date, or a Time. It's an interval (specifically, it's a DateInterval string representation ).
You need a baseline DateTime to add that interval.
Try something along these lines
$interval = $dv = new DateInterval('PT1H8M21S'); //the value you get from the url
$time = new DateTime('2000-01-01'); //any date works fine here.
// Note: Hours, mins and seconds == 0
$time->add($interval);
echo $time->format('H:i:s');
First, create the proper DateInterval object from the string you received.
Then, create a baseline DateTime object. Any date is ok, you just need to make sure that you have hours, minutes and seconds (I'm assuming that the interval will always be less than one full day.)
Add the interval to the baseline date and echo the hours, minutes and seconds as you wish.
If you think that 1H8M21S means 1 Hour 8 minute & 21 seconds then use preg macth to get the values.
$str = 'PT1H8M21S';preg_match('/PT(.+)H(.*)/', $str, $m);echo $m[1];
Try to use str_replace function like this
$time = "PT1H8M21S";
$time = str_replace("PT", "", $time);
$time = str_replace("H", ":", $time);
$time = str_replace("M", ":", $time);
$time = str_replace("S", "", $time);
echo $time;
maybe you can add zero padding in your final string if you like it
preg_match('/PT(.+)H(.+)M(.+)S$/', $str, $m3); echo $m3[1].":".$m3[2].":".$m3[3]
change $youtube_time to your interval variable
$youtube_time = 'PT1H8M21S';
$duration = new DateInterval($youtube_time);
$videoDuration = (60 * 60 * $duration->h) + (60 * $duration->i) + $duration->s;
print gmdate("H:i:s", $videoDuration);