Created
January 30, 2012 22:27
-
-
Save joshwnj/1707199 to your computer and use it in GitHub Desktop.
Creating ISO 8601 durations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$parts = secondsToDuration(61); | |
assert($parts['hours'] === 0); | |
assert($parts['minutes'] === 1); | |
assert($parts['seconds'] === 1); | |
assert('PT0H1M1S' === formatDuration($parts)); | |
$parts = secondsToDuration(7202); | |
assert($parts['hours'] === 2); | |
assert($parts['minutes'] === 0); | |
assert($parts['seconds'] === 2); | |
assert('PT2H0M2S' === formatDuration($parts)); | |
$parts = secondsToDuration(0); | |
assert($parts['hours'] === 0); | |
assert($parts['minutes'] === 0); | |
assert($parts['seconds'] === 0); | |
assert('PT0H0M0S' === formatDuration($parts)); | |
echo "all passed\n"; | |
// ---- | |
/** | |
* Convert a number of seconds to whole numbers of hours, minutes, seconds | |
* @param {int} | |
* @return {hash} | |
*/ | |
function secondsToDuration ($seconds) { | |
$remaining = $seconds; | |
$parts = array(); | |
$multipliers = array( | |
'hours' => 3600, | |
'minutes' => 60, | |
'seconds' => 1 | |
); | |
foreach ($multipliers as $type => $m) { | |
$parts[$type] = (int)($remaining / $m); | |
$remaining -= ($parts[$type] * $m); | |
} | |
return $parts; | |
} | |
/** | |
* Format a duration as ISO 8601 | |
* @param {hash} | |
* @return {string} | |
*/ | |
function formatDuration ($parts) { | |
$default = array( | |
'hours' => 0, | |
'minutes' => 0, | |
'seconds' => 0 | |
); | |
extract(array_merge($default, $parts)); | |
return "PT{$hours}H{$minutes}M{$seconds}S"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment