This question already has answers here:
Compare two dates with JavaScript

(40个答案)


1年前关闭。




比较多个日期时需要了解日期的工作原理
console.log(new Date('2019-10-10T05:00:00.000+0000') >= new Date('2019-10-10T10:30:00.000+0530')) // true
console.log(new Date('2019-10-10T05:00:00.000+0000') <= new Date('2019-10-10T10:30:00.000+0530')) // true
console.log(new Date('2019-10-10T05:00:00.000+0000') == new Date('2019-10-10T10:30:00.000+0530')) // false
console.log(+new Date('2019-10-10T05:00:00.000+0000') == +new Date('2019-10-10T10:30:00.000+0530')) // true

前两个语句如何返回true,而第三个语句返回false。请要求说明/链接。

最佳答案

在第三个比较中:

console.log(new Date('2019-10-10T05:00:00.000+0000') == new Date('2019-10-10T10:30:00.000+0530')) // false

您只是在比较两个不是完全相同的对象,因此返回false。 MDN解释:



第四个比较:
console.log(+new Date('2019-10-10T05:00:00.000+0000') == +new Date('2019-10-10T10:30:00.000+0530')) // true

通过使用+符号强制转换为数字。

对于第一次和第二次比较:
console.log(new Date('2019-10-10T05:00:00.000+0000') >= new Date('2019-10-10T10:30:00.000+0530')) // true
console.log(new Date('2019-10-10T05:00:00.000+0000') <= new Date('2019-10-10T10:30:00.000+0530')) // true

MDN解释了< <= > >=关系运算符的行为:



因此它对返回数字的valueOf()date对象调用timestamps函数,从而求值为true

10-05 21:16
查看更多