Last active
August 29, 2015 14:04
-
-
Save srgoogleguy/94af2ea035fa80fc920c to your computer and use it in GitHub Desktop.
Time Spec
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 | |
/** | |
* Translate a clock formatted string into a sum of seconds | |
* e.g. toSec("3:20") == 200 | |
*/ | |
function toSec($clock) { | |
$eq = array(1, 60, 3600, 86400); | |
$seconds = 0; | |
$parts = explode(':', $clock, count($eq)); | |
$parts = array_reverse($parts); | |
foreach($parts as $i => $part) { | |
$seconds += $part * $eq[$i]; | |
} | |
return $seconds; | |
} | |
/** | |
* Translate a sum of seconds into clock format (opposite of toSec) | |
* e.g. toClock(200) == "3:20" | |
*/ | |
function toClock($seconds) { | |
$m = array('d' => 86400, 'h' => 3600, 'm' => 60, 's' => 1); | |
$p = array('d' => 0, 'h' => 0, 'm' => 0, 's' => 0); | |
foreach($m as $i => $d) { | |
$s = floor($seconds / $d); | |
$seconds -= $s * $d; | |
$p[$i] = (($i == 'h' && $p['d'] == '00') || $i == 'd') ? $s : sprintf('%02d', $s); | |
} | |
if ($p['d'] == "00") { | |
unset($p['d']); | |
} | |
if (empty($p['h'])) { | |
unset($p['h']); | |
} | |
$e = array_shift($p); | |
if (strlen($e) > 1 && $e[0] == 0) { | |
$e = substr($e, 1); | |
} | |
array_unshift($p, $e); | |
return implode(':', $p); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment