Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
convert milliseconds to digital style time, ex: 12:59:59
/**
* 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(":")
};
}
@asabaylus
Copy link
Author

asabaylus commented Mar 11, 2011

Usage


var result = convertMilliseconds(3661000, "hh:m:s");

result.hours;    // --> 1 hour 
result.minuets;  // --> 1 min
result.seconds;  // --> 1 sec
result.clock;    // --> "01:1:1"

More Examples

convertMilliseconds(milliseconds, pattern);

convertMilliseconds(3661000);
convertMilliseconds(3661000, "hh:mm:ss");
convertMilliseconds(3661000, "mm:hh:ss");
convertMilliseconds(3661000, "ss:mm:hh");
convertMilliseconds(3661000, "mm:ss");
convertMilliseconds(3661000, "ss");
convertMilliseconds(3661000, "h:m:s");
convertMilliseconds(3661000, "m:s");
convertMilliseconds(3661000, "s");

// convertMilliseconds returns object...

var obj = convertMilliseconds(3661000);
obj.hours === 1
obj.minuets === 1
obj.seconds === 1
obj.clock === "01:01:01"

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