Convert youtube Api v3 video duration in php

2019-01-19 10:30发布

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;
        }

12条回答
乱世女痞
2楼-- · 2019-01-19 11:10

DateTime and DateInterval not working in Yii or some php version. So this is my solution. Its work with me.

function convertTime($time){        
    if ($time > 0){
        $time_result = '';
        $hours = intval($time / 3600);
        if ($hours > 0)
            $time_result = $time_result.$hours.':';
        $time = $time % 3600;
        $minutes = intval($time / 60);
        $seconds = $time % 60;
        $time_result = $time_result.(($minutes > 9)?$minutes:'0'.$minutes).':';
        $time_result = $time_result.(($seconds > 9)?$seconds:'0'.$seconds);
    }else 
        $time_result = '0:00';        

    return $time_result;
}
查看更多
够拽才男人
3楼-- · 2019-01-19 11:15

You should take a look at your $parts variable after it's created.

var_dump($parts);

Compare that output with how you are defining your variables. It should stand out pretty obviously after that.

I guess my next question after that is what variations of the input time string are you expecting and what validation will you be doing? The variations of the input format you want to handle will affect the complexity of the actual code written.

Edit: Here is an updated function to handle missing numeric values (if the hours or minutes is omitted) and seconds/hours over 60 (not sure if this will ever happen). This doesn't validate the label for the numbers:

  • 1 number: assume it is seconds
  • 2 numbers: assume it is minutes, seconds
  • 3 or more numbers: assume first 3 numbers are hours, minutes, seconds (ignoring another numbers)

More validation can be added to look into validating the input string.

<?php
function covtime($youtube_time) {
    preg_match_all('/(\d+)/',$youtube_time,$parts);

    // Put in zeros if we have less than 3 numbers.
    if (count($parts[0]) == 1) {
        array_unshift($parts[0], "0", "0");
    } elseif (count($parts[0]) == 2) {
        array_unshift($parts[0], "0");
    }

    $sec_init = $parts[0][2];
    $seconds = $sec_init%60;
    $seconds_overflow = floor($sec_init/60);

    $min_init = $parts[0][1] + $seconds_overflow;
    $minutes = ($min_init)%60;
    $minutes_overflow = floor(($min_init)/60);

    $hours = $parts[0][0] + $minutes_overflow;

    if($hours != 0)
        return $hours.':'.$minutes.':'.$seconds;
    else
        return $minutes.':'.$seconds;
}
查看更多
走好不送
4楼-- · 2019-01-19 11:24

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

查看更多
男人必须洒脱
5楼-- · 2019-01-19 11:24

Here is the complete code to get, convert and display the video duration

$vidkey = "           " ; // for example: cHPMH26sw2f
$apikey = "xxxxxxxxxxxx" ;

$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey");
$VidDuration =json_decode($dur, true);
foreach ($VidDuration['items'] as $vidTime) 
{
$VidDuration= $vidTime['contentDetails']['duration'];
}
// convert duration from ISO to M:S
$date = new DateTime('2000-01-01');
$date->add(new DateInterval($VidDuration));
echo $date->format('i:s') ;

Replace xxxxxxx with your API Key Results: 13:07

查看更多
贼婆χ
6楼-- · 2019-01-19 11:26

You can try this -

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

查看更多
▲ chillily
7楼-- · 2019-01-19 11:27

Why the complication. Think outside the box.

    $seconds = substr(stristr($length, 'S', true), -2, 2);
    $seconds = preg_replace("/[^0-9]/", '', $seconds);
    $minutes =  substr(stristr($length, 'M', true), -2, 2);
    $minutes = preg_replace("/[^0-9]/", '', $minutes);
    $hours =  substr(stristr($length, 'H', true), -2, 2);
    $hours = preg_replace("/[^0-9]/", '', $hours);

OK. preg_replace is not really needed, but I put it to guarantee only numbers.

Then for my formatting (which you can do however you like without limits),

      if($hours == 0){ 
      $h= '';
      }else{ 
      $h= $hours.':';
      }

      if($minutes <10){ 
      $m= '0'.$minutes.':'; 
        if($h == ''){
        $m= $minutes.':'; 
        }
          if ($minutes == 0){
            $m= $minutes;                 
          }
      }else{ 
      $m= $minutes.':';
      }

      if($seconds <10){ 
      $s= '0'.$seconds; 
      }else{ 
      $s= $seconds;
      }
      $time= $h . $m . $s.'s';
查看更多
登录 后发表回答