Skip to content

Instantly share code, notes, and snippets.

@w0rldart
Created September 12, 2015 12:31
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save w0rldart/9e10aedd1ee55fc4bc74 to your computer and use it in GitHub Desktop.
Save w0rldart/9e10aedd1ee55fc4bc74 to your computer and use it in GitHub Desktop.
ISO 8601 to seconds
/**
* Convert ISO 8601 values like PT15M33S
* to a total value of seconds.
*
* @param string $ISO8601
*/
function ISO8601ToSeconds($ISO8601)
{
preg_match('/\d{1,2}[H]/', $ISO8601, $hours);
preg_match('/\d{1,2}[M]/', $ISO8601, $minutes);
preg_match('/\d{1,2}[S]/', $ISO8601, $seconds);
$duration = [
'hours' => $hours ? $hours[0] : 0,
'minutes' => $minutes ? $minutes[0] : 0,
'seconds' => $seconds ? $seconds[0] : 0,
];
$hours = substr($duration['hours'], 0, -1);
$minutes = substr($duration['minutes'], 0, -1);
$seconds = substr($duration['seconds'], 0, -1);
$toltalSeconds = ($hours * 60 * 60) + ($minutes * 60) + $seconds;
return $toltalSeconds;
}
echo ISO8601ToSeconds('PT15M33S'); // Returns a value of 933
@RuudBurger
Copy link

Found this gist through Google, and got warnings because you're doing math with numbers in stringformat ($hours, $minutes, $seconds). Here is a simplified version if you are using PHP 5.3 and up.
Including support for days in the input.

/**
 * Convert ISO 8601 values like P2DT15M33S
 * to a total value of seconds.
 *
 * @param string $ISO8601
 */
function ISO8601ToSeconds($ISO8601){
	$interval = new \DateInterval($ISO8601);

	return ($interval->d * 24 * 60 * 60) +
		($interval->h * 60 * 60) +
		($interval->i * 60) +
		$interval->s;
}

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

@ficus
Copy link

ficus commented Jun 15, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment