使用JavaScript比较两个日期不能按预期工作 [英] Comparing two dates using JavaScript not working as expected
本文介绍了使用JavaScript比较两个日期不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的JavaScript代码:
Here is my javascript code:
var prevDate = new Date('1/25/2011'); // the string contains a date which
// comes from a server-side script
// may/may not be the same as current date
var currDate = new Date(); // this variable contains current date
currDate.setHours(0, 0, 0, 0); // the time portion is zeroed-out
console.log(prevDate); // Tue Jan 25 2011 00:00:00 GMT+0500 (West Asia Standard Time)
console.log(currDate); // Tue Jan 25 2011 00:00:00 GMT+0500 (West Asia Standard Time)
console.log(prevDate == currDate); // false -- why oh why
请注意,两个日期是一样的,但使用 ==
表示它们不一样。为什么?
Notice that both dates are the same but comparing using ==
indicates they are not the same. Why?
推荐答案
我不认为你可以使用 ==
比较JavaScript中的日期。这是因为它们是两个不同的对象,所以它们不是对象相等。 JavaScript允许您使用 ==
比较字符串和数字,但所有其他类型都作为对象进行比较。
I don't think you can use ==
to compare dates in JavaScript. This is because they are two different objects, so they are not "object-equal". JavaScript lets you compare strings and numbers using ==
, but all other types are compared as objects.
:
var foo = "asdf";
var bar = "asdf";
console.log(foo == bar); //prints true
foo = new Date();
bar = new Date(foo);
console.log(foo == bar); //prints false
foo = bar;
console.log(foo == bar); //prints true
但是,您可以使用 getTime
方法获取可比较的数值:
However, you can use the getTime
method to get comparable numeric values:
foo = new Date();
bar = new Date(foo);
console.log(foo.getTime() == bar.getTime()); //prints true
这篇关于使用JavaScript比较两个日期不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文