Javascript - 具有多个偏移量比较的相同日期

Javascript - same Date with multiple offset comparison

需要了解比较多个日期时日期的工作原理

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

为什么前两个陈述 returns 正确而第三个错误。请请求explanation/links。

第三次比较:

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

你只是在比较两个不是同一个对象的对象,因此 returns 错误。 MDN 说明:

Two distinct objects are never equal for either strict or abstract comparisons.

第四次比较:

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 解释了 < <= > >= 关系运算符的行为:

Each of these operators will call the valueOf() function on each operand before a comparison is made.

因此它在 date 对象上调用 valueOf() 函数返回 timestamps,即 数字 ,因此计算结果为 true

MDN Date page 在页面顶部包含此内容:

var date1 = new Date('December 17, 1995 03:24:00');
var date2 = new Date('1995-12-17T03:24:00');

console.log(date1 === date2);
// expected output: false;

*编辑:有人指出,根据区域设置和 JavaScript 实现,MDN 示例中的这两个日期实际上可能 相同。但是,使用以下方法可以获得相同的结果:

var date1 = new Date('1995-12-17T03:24:00');
var date2 = new Date('1995-12-17T03:24:00');

console.log(date1 === date2);
// expected output: false;

相等运算符不 return 的原因是因为 Date 对象是......好吧......对象。 JavaScript 只有当字面意思是同一个对象时 return 才相等。

JavaScript 认为两个具有相同属性的对象不相等(想象一下,要对一个对象中的每个 属性 进行递归分析,算法将有多么复杂!)

var a = {test:1};
var b = a;
var c = {test:1};
console.log(a===b) // true
console.log(a===c) // false

This Whosebug answer 解释了如何使用 getTime:

来测试日期是否相等
var same = d1.getTime() === d2.getTime();

这样你比较的是数字(纪元)而不是对象。

我认为这是因为当您比较 Date 对象时,您实际上是在比较对象,如果比较是否相等(假设对象不是相同)。 '==' 检查对象引用是否相同,而不是属性。因此在你的第三种情况下结果为假。

但是,当您在前面添加一个 + 时,日期会被强制转换为一个数字(如果是日期,则为距纪元的毫秒数),您可以通过对日期对象使用 getTime() 方法来获得相同的结果。