5

我试图获得 2 个不同时间之间的时差,并且我在几小时和几分钟内都得到了正确的时间差。但如果第二个大于第一个,就会出现问题。时间显示为负数。

例如

Start time : 00:02:59
End time   : 00:05:28

如果我得到开始时间和结束时间之间的差异

00:05:28 - 00:02:59 = 00:3:-31

这不是一个正确的值。我正在使用以下脚本来获取此值。

var start_time = $("#startTime").val();
var end_time = $("#endTime").val();
var startHour = new Date("01/01/2007 " + start_time).getHours();
var endHour = new Date("01/01/2007 " + end_time).getHours();
var startMins = new Date("01/01/2007 " + start_time).getMinutes();
var endMins = new Date("01/01/2007 " + end_time).getMinutes();
var startSecs = new Date("01/01/2007 " + start_time).getSeconds();
var endSecs = new Date("01/01/2007 " + end_time).getSeconds();
var secDiff = endSecs - startSecs;
var minDiff = endMins - startMins;
var hrDiff = endHour - startHour;
alert(hrDiff+":"+minDiff+":"+secDiff);

任何人都请告诉我如何正确获得两次之间的时差,即使考虑秒数

4

1 回答 1

-7

尝试这样做

    var date1 = new Date(2000, 0, 1,  9, 0); // 9:00 AM
    var date2 = new Date(2000, 0, 1, 17, 0); // 5:00 PM
    if (date2 < date1) {
        date2.setDate(date2.getDate() + 1);
    }
    var diff = date2 - date1;
    // 28800000 milliseconds (8 hours)

然后,您可以将毫秒转换为小时、分钟和秒,如下所示:

    var msec = diff;
    var hh = Math.floor(msec / 1000 / 60 / 60);
    msec -= hh * 1000 * 60 * 60;
    var mm = Math.floor(msec / 1000 / 60);
    msec -= mm * 1000 * 60;
    var ss = Math.floor(msec / 1000);
    msec -= ss * 1000;
    // diff = 28800000 => hh = 8, mm = 0, ss = 0, msec = 0
于 2013-08-26T10:27:51.247 回答