两个相同的 JavaScript 日期不相等
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15470403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Two identical JavaScript dates aren't equal
提问by Bryce
When I create two identical JavaScript Date
objects and then compare them, it appears that they are not equal. How to I test if two JavaScript dates have the same value?
当我创建两个相同的 JavaScriptDate
对象然后比较它们时,它们似乎不相等。如何测试两个 JavaScript 日期是否具有相同的值?
var date1 = new Date('Mon Mar 11 2013 00:00:00');
var date2 = new Date('Mon Mar 11 2013 00:00:00');
console.log(date1 == date2); //false?
回答by Bryce
It appears this has been addressed already.
看来这已经解决了。
To check whether dates are equal, they must be converted to their primitives:
要检查日期是否相等,必须将它们转换为它们的原语:
date1.getTime()=== date2.getTime()
//true
回答by sachinjain024
First of all, you are making a sound mistake here of comparing the references. Have a look at this:
首先,您在比较参考文献时犯了一个错误。看看这个:
var x = {a:1};
var y = {a:1};
// Looks like the same example huh!
alert (x == y); // It says false
Here, although the objects look identical but they hold diferent slots in memory. Reference store only the address of the object. Hence both references are different.
在这里,虽然对象看起来相同,但它们在内存中拥有不同的插槽。引用只存储对象的地址。因此,两个参考是不同的。
So now, we have to compare the values since you know reference comparison won't work here. You can just do
所以现在,我们必须比较这些值,因为您知道参考比较在这里不起作用。你可以做
if (date1 - date2 == 0) {
// Yep! Dates are equal
} else {
// Handle different dates
}
回答by user3175004
I compare many kinds of values in a for loop, so I wasn't able to evaluate them by substracting, instead I coverted values to string before comparing
我在 for 循环中比较了多种值,所以我无法通过减法来评估它们,而是在比较之前将值转换为字符串
var a = [string1, date1, number1]
var b = [string2, date2, number2]
for (var i in a){
if(a.toString() == b.toString()){
// some code here
}
}