Javascript日期比较很奇怪

时间:2016-02-11 12:28:01

标签: javascript date datetime

我觉得这应该存在于代码高尔夫帖子中,但是以下行为导致了一个奇怪的错误并且表面上看起来不可思议:

"

** 修改 ** 请记录在哪里?

2 个答案:

答案 0 :(得分:4)

===之外的所有比较都是将日期强制转换为数字(它们的时间值,自The Epoch以来的毫秒数),然后比较这些数字。 ===比较是检查ab是否引用相同的对象。 (==会做同样的事情。)

时间(在您的示例中)完全相同,但仍有两个不同的对象。因此,你看到的结果。

注释:

// Create two Date instances, check if a's time value is less than b's
// (probably not, but it's just feasible this could cross a millisecond
// threshold)
(a = new Date()) < (b = new Date())

// Show the value of a and b
a  // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)
b  // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)

// See if a's time value is less than b's
a < b    // false

// See if a and b refer to the same object (they don't)
a === b  // false

// See if a's time value is greater than b's
a > b    // false

// See if a's time value is less than or equal to b's
a <= b   // true

// See if a's time value is greater than or equal to b's
a >= b  

或者换句话说,你的代码基本上是这样做的(请注意+符号的位置和不是):

(a = new Date()) < (b = new Date())
a  // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)
b  // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)
+a < +b    // false
a === b    // false
+a > +b    // false
+a <= +b   // true
+a >= +b  

请注意,如果时间完全相同,则+a === +b(或+a == +b或 - 非常棘手 - +a == ba == +b)都将成立,因为我们我要比较时间价值。

只是为了好玩,这里有一个例子,我们知道基础时间值是完全相同的:

var a, b;
var now = Date.now(); // = +new Date(); on old browsers
show("create and compare: ", (a = new Date(now)) < (b = new Date(now)), "a's time is not < b's");
show("+a < +b:   ", +a < +b,   "a's time is not < b's");
show("a < b:     ", a < b,     "a's time is not < b's");
show("a === b:   ", a === b,   "a and b don't refer to the same object");
show("a == b:    ", a == b,    "a and b don't refer to the same object");
show("+a === +b: ", +a === +b, "their time values are the same");
show("+a == +b:  ", +a == +b,  "their time values are the same");
show("+a > +b:   ", +a > +b,   "a's time is not > b's");
show("a > b:     ", a > b,     "a's time is not > b's");
show("+a <= +b:  ", +a <= +b,  "a's time is equal to b's");
show("a <= b:    ", a <= b,    "a's time is equal to b's");
show("+a >= +b:  ", +a >= +b,  "a's time is equal to b's   ");
show("a >= b:    ", a >= b,    "a's time is equal to b's   ");

function show(prefix, result, because) {
    var msg = prefix + result + ", " + because;
    var pre = document.createElement('pre');
    pre.innerHTML = msg.replace(/&/g, "&amp;").replace(/</g, "&lt;");
    document.body.appendChild(pre);
}

答案 1 :(得分:0)

要比较您需要使用的日期.getTime()。所以正确的比较应该是:

a.getTime() === b.getTime() //true
a.getTime() > b.getTime()   //false
...