本文介绍了JavaScript日期对象比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在比较Javascript中的日期对象时,我发现即使比较相同的日期也不会返回true。

When comparing date objects in Javascript I found that even comparing the same date does not return true.

 var startDate1 = new Date("02/10/2012");
 var startDate2 = new Date("01/10/2012");
 var startDate3 = new Date("01/10/2012");
 alert(startDate1>startDate2); // true
 alert(startDate2==startDate3); //false

我如何比较这些日期的相等性?我有兴趣利用JS的原生 Date 对象,而不是任何第三方库,因为它不适合使用第三方JS来比较日期。

How could I compare the equality of these dates? I am interested in utilizing the native Date object of JS and not any third party libraries since its not appropriate to use a third party JS just to compare the dates.

推荐答案

这是因为在第二种情况下,比较实际日期对象,并且两个对象永远不会彼此相等。强制他们编号:

That is because in the second case, the actual date objects are compared, and two objects are never equal to each other. Coerce them to number:

 alert( +startDate2 == +startDate3 ); // true

如果您想要更明确地转换为数字,请使用:

If you want a more explicity conversion to number, use either:

 alert( startDate2.getTime() == startDate3.getTime() ); // true

 alert( Number(startDate2) == Number(startDate3) ); // true

哦,对规范的引用:§11.9.3,基本上说在比较对象时, obj1 == obj2 仅当它们引用同一个对象时才为真,否则结果为false。

Oh, a reference to the spec: §11.9.3 The Abstract Equality Comparison Algorithm which basically says when comparing objects, obj1 == obj2 is true only if they refer to the same object, otherwise the result is false.

这篇关于JavaScript日期对象比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 05:30