1

我需要使用 Javascript 以这种格式获取时差:“HH:MM:SS”。

我试过这个:

var diff = Date.parse( time2) - Date.parse( time1 );
var total_time = (diff / 1000 / 60 / 60) + ":" + (diff / 1000 / 60) + ":" + (diff / 1000);

还有这个:

var diff = new Date( time2) - new Date( time1 );
var total_time = (diff / 1000 / 60 / 60) + ":" + (diff / 1000 / 60) + ":" + (diff / 1000);

这些是 time2 和 time1 的值:

time1: "2012-11-07 15:20:32.161"
time2: "2012-11-07 17:55:41.451"

在这两种情况下我得到的结果是:

total_time= 0.5250819444444444:31.504916666666666:1890.295

你可以看到是不正确的

4

2 回答 2

2

我认为你得到了错误的差异值,因为日期中的毫秒部分由.. 它没有被数据解析器正确接受。

尝试使用不包括毫秒的日期和时间部分,如下所示:

 var diff = Date.parse(time2.split(".")[0]) - Date.parse( time1.split(".")[0]);

此外,当你得到错误的差异diff时,你的时间计算也是错误的。

它应该是:

       var second = Math.floor(diff /1000);
        //convert the seconds into minutes and remainder is updated seconds value
       var minute = Math.floor(second /60);
       second = second % 60;

        //convert the minutes into hours and remainder is updated minutes value
       var hour = Math.floor(minute/60);
       minute = minute %60;

       var total_time= hour+":" minute+":"+second;
于 2012-11-08T19:36:27.343 回答
1

您忘记删除已计算的毫秒数diff。这是一个非常详细的示例,说明您如何以适当的方式进行操作。

var time1 = "2012-11-07 15:20:32.161",
    time2 = "2012-11-07 17:55:41.451",

    SECOND = 1000,
    MINUTE = SECOND* 60,
    HOUR = MINUTE* 60;

var diff = new Date(time2) - new Date(time1);

var hours = Math.floor(diff / HOUR); // Calculate how many times a full hour fits into diff
diff = diff - (hours * HOUR); // Remove hours from difference, we already caluclated those
var minutes = Math.floor(diff / MINUTE); // Calculate how many times a full minute fits into diff
diff = diff - (minutes * MINUTE); // Remove minutes from difference
var seconds = Math.floor(diff / SECOND); // As before
diff = diff - (seconds * SECOND);
var rest = diff;

var total_time = hours + ":" + minutes + ":" + seconds + " " + rest ;

演示

于 2012-11-08T19:42:42.830 回答