PHP - Convert ISO8601 standard (used by YouTube) for seconds

1

I need to convert for seconds a time received in the ISO8601 standard, used by YouTube. Does anyone know of any function for this purpose?

Exemplifying:

If I took the YouTube API for the length of a PT1M31S video, I would like to convert all this to seconds only. Is there a native PHP function for this? In this example the result would be 91 seconds .

    
asked by anonymous 26.11.2015 / 22:06

2 answers

3

Here is an example PHP function to convert the YouTube duration format to seconds:

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

   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;

   $conv = $hours.':'.$minutes.':'.$seconds;

   sscanf($conv, "%d:%d:%d", $hours, $minutes, $seconds);
   $time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;

   return $time_seconds;
}
    
27.11.2015 / 16:08
5

PT1M31S is a time format, means a time period of 1 minute and 31 seconds, then treat this string as a DateTime.  Create a new date and add this interval using the add () method, which takes as an argument DateInterval which is exactly the string  PT1M31S, done this just convert the 01:31 in seconds using date_parsed ()

$duracao = new DateTime('@0');
$duracao->add(new DateInterval('PT1M31S'));

$parsed = date_parse($duracao->format('H:i:s'));
$segundos = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];

echo $segundos;

Or in a simplified way, create a DateInterval object to translate the time period into hours / minutes / seconds and then perform the calculation to convert these values in seconds. If I use this code in several places, I suggest that you change the values 3600 and 60 by constants to give more semantics, eg: const SEGUNDOS_EM_UMA_HORA = 3600

$intervalo = new DateInterval('PT1M31S');
$segundos = $intervalo->h * 3600 + $intervalo->i * 60 + $intervalo->s; 
echo $segundos;

Based on:

Convert youtube Api v3 video duration in php

How to convert "HH: MM: SS" string to seconds with PHP?

    
27.11.2015 / 16:46