convert milliseconds to digital style time, ex: 12:59:59
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
/** | |
* Convert milliseconds in regular style time | |
* @author Asa Baylus | |
**/ | |
function convertMilliseconds (ms, p) { | |
var pattern = p || "hh:mm:ss", | |
arrayPattern = pattern.split(":"), | |
clock = [ ], | |
hours = Math.floor ( ms / 3600000 ), // 1 Hour = 36000 Milliseconds | |
minutes = Math.floor (( ms % 3600000) / 60000), // 1 Minutes = 60000 Milliseconds | |
seconds = Math.floor ((( ms % 360000) % 60000) / 1000) // 1 Second = 1000 Milliseconds | |
// build the clock result | |
function createClock(unit){ | |
// match the pattern to the corresponding variable | |
if (pattern.match(unit)) { | |
if (unit.match(/h/)) { | |
addUnitToClock(hours, unit); | |
} | |
if (unit.match(/m/)) { | |
addUnitToClock(minutes, unit); | |
} | |
if (unit.match(/s/)) { | |
addUnitToClock(seconds, unit); | |
}; | |
} | |
} | |
function addUnitToClock(val, unit){ | |
if ( val < 10 && unit.length === 2) { | |
val = "0" + val; | |
} | |
clock.push(val); // push the values into the clock array | |
} | |
// loop over the pattern building out the clock result | |
for ( var i = 0, j = arrayPattern.length; i < j; i ++ ){ | |
createClock(arrayPattern[i]); | |
} | |
return { | |
hours : hours, | |
minutes : minutes, | |
seconds : seconds, | |
clock : clock.join(":") | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
More Examples