JQuery - 格式化毫秒到HH:MM:SS:sss

时间:2013-10-21 20:04:35

标签: jquery milliseconds

我尝试使用此函数格式化持续时间(以毫秒为单位),但它对我不起作用:

var msec_num      = parseInt(duration, 10) / 100; 
var hours        = Math.floor(msec_num / 3600 );
var minutes      = Math.floor((msec_num - (hours * 3600)) / 60);
var seconds      = Math.floor((msec_num - (hours * 3600) - (minutes * 60)) / 60 / 1000 );
var milliseconds = ( msec_num - ((hours * 3600) - (minutes * 60) - (seconds)) / 1000 ) * 100;

if (hours   < 10) {hours   = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
if (milliseconds < 10) {milliseconds = "0"+milliseconds;}

var time    = hours + ":" + minutes + ":" + seconds + ":" + milliseconds;

如果我测试使用值(持续时间= 1091毫秒)它给我这个:00:00:00:1091 ???

我如何才能弄清楚所有价值是否完美?

4 个答案:

答案 0 :(得分:2)

看起来您遇到100而不是1000

的问题
var duration = 1091;
var milliseconds = (duration % 1000); duration = Math.floor(duration/1000);
var seconds = (duration % 60); duration = Math.floor(duration/60);
var minutes = (duration % 60); duration = Math.floor(duration/60);
var hours = duration;

答案 1 :(得分:2)

使用duration的“Moment.js”轻松实现!

var duration = moment.duration(parseInt(duration, 10));
var addZero = function(v) { return (v<10 ? '0' : '') + Math.floor(v); };

var time = addZero(duration.hours()) +
     ':' + addZero(duration.minutes()) +
     ':' + addZero(duration.seconds()) +
     ':' + addZero(duration.milliseconds());

答案 2 :(得分:1)

试试这个 - Moment.js - 一个javascript日期库,用于解析,验证,操作和格式化日期。

答案 3 :(得分:0)

如果我阅读了Moment.js的文档,那就容易多了:

moment(parseInt(duration, 10)).format('h:mm:ss');

如果我错了,请纠正我。