在JS中获得时间差是不准确的

时间:2013-01-17 07:53:56

标签: javascript html5 date

我在JavaScript中有一个功能来区分两次:

function get_time_difference(laterDate) {
    var earlierDate = new Date();//Now
    var nTotalDiff = laterDate.getTime() - earlierDate.getTime();
    var oDiff = new Object();

    oDiff.days = Math.floor(nTotalDiff / 1000 / 60 / 60 / 24);
    nTotalDiff -= oDiff.days * 1000 * 60 * 60 * 24;

    oDiff.hours = Math.floor(nTotalDiff / 1000 / 60 / 60);
    nTotalDiff -= oDiff.hours * 1000 * 60 * 60;

    oDiff.minutes = Math.floor(nTotalDiff / 1000 / 60);
    nTotalDiff -= oDiff.minutes * 1000 * 60;

    oDiff.seconds = Math.floor(nTotalDiff / 1000);

    if (0 == oDiff.minutes && 0 == oDiff.hours) {
        //Do Something
    }
    return oDiff.minutes;
}

当时间相等时,我需要运行一个特定的函数,

我的问题是有时他会返回59分钟,而它应该返回0 ..

为什么会这样?我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

我这样修理:

function get_time_difference(laterDate) {

var earlierDate = new Date(); //Now
var oDiff = new Object();

oDiff.days = laterDate.getDate() - earlierDate.getDate();
oDiff.hours = laterDate.getHours() - earlierDate.getHours();
oDiff.minutes = laterDate.getMinutes() - earlierDate.getMinutes();
oDiff.seconds = laterDate.getSeconds() - earlierDate.getSeconds();

if (0 == oDiff.minutes && 0 == oDiff.hours) {
//Do Something
}
   return oDiff.minutes;
}

答案 1 :(得分:0)

制作

function get_time_difference(laterDate) {

var earlierDate = new Date();//Now
var nTotalDiff = laterDate.getTime() - earlierDate.getTime();
var oDiff = new Object();

oDiff.days = Math.floor(nTotalDiff / (1000 * 60 * 60 * 24 ));
nTotalDiff -= oDiff.days * 1000 * 60 * 60 * 24;

oDiff.hours = Math.floor(nTotalDiff / (1000 * 60 * 60 ));
nTotalDiff -= oDiff.hours * 1000 * 60 * 60;

oDiff.minutes = Math.floor(nTotalDiff / (1000 * 60 ));
nTotalDiff -= oDiff.minutes * 1000 * 60;

oDiff.seconds = Math.floor(nTotalDiff / 1000);

if (0 == oDiff.minutes && 0 == oDiff.hours) {
//Do Something
}
return oDiff.minutes;

}

您只需确保首先评估您要分割的内容