How to convert ISO 8601 duration returned by API to DateTime

/**
 * Convert ISO 8601 values like P20DT15M33S
 * to a total value of seconds.
 *
 * @param string $ISO8601
 */
function ISO8601ToSeconds($ISOString){
    $interval = new \DateInterval($ISOString);
    $seconds = $interval->d * 86400 +     //24 * 60 * 60 = 86400
               $interval->h * 3600 +      // 60 * 60 = 3600   
               $interval->i * 60 +        
               $interval->s;
   return (int) $seconds;
}

echo ISO8601ToSeconds('P20DT15M33S'); // Returns a value of 1728933

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *