Javascript日期比较很奇怪

Javascript Date comparison is bizarre

本文关键字:比较 日期 Javascript      更新时间:2023-09-26

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

(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 (correct)
a === b  // false (incorrect)  <<<
a > b    // false (correct)
a <= b   // true (correct)
a >= b   // true (correct)
**

编辑 **请问这在哪里记录?

除了

===比较之外,您所有的比较都将日期强制为数字(它们的时间值,自纪元以来的毫秒数),然后比较这些数字。===比较是检查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);
}

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

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