javascript milliseconds to time format


// 換算ms時間成一般時間格式
function getTimeString(total_ms) {
var ms = 0, sec = 0, min = 0, hour = 0;

ms = total_ms % 1000;
sec = parseInt((total_ms - ms) / 1000);
if (sec != 0) min = Math.floor(sec / 60);
if (min != 0) hour = Math.floor(min / 60);

return (hour > 0 ? formatNumberLength(hour, 2) + ":" : "")
+ (min > 0 ? formatNumberLength(min % 60, 2) + ":" : "")
+ (sec > 0 ? formatNumberLength(sec % 60, 2) : "00")
+ "." + formatNumberLength(ms, 3);
}

// 將數值轉成指定長度的字串
function formatNumberLength(oNumber, oLength) {
var str = parseInt(oNumber).toString();
while(str.length < oLength) {
str = '0' + str;
}
return str;
}

<><> 結果範例 <><>

ms:
Result:

留言

這個網誌中的熱門文章

HTML - CSS - footer floating toolbar bottom 瓢浮置底的工具列

jQuery - header & floating menu - dynamic detect & adjust

javascript - 樂透 lottery - 號碼產生器