使用JavaScript比较两个日期未按预期工作
以下是我的javascript代码:使用JavaScript比较两个日期未按预期工作,javascript,datetime,date,comparison,Javascript,Datetime,Date,Comparison,以下是我的javascript代码: 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 va
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
请注意,两个日期相同,但使用
=
进行比较表明它们不相同。为什么?JS使用
和来比较日期,我认为您不能使用=
来比较JavaScript中的日期。这是因为它们是两个不同的对象,所以它们不是“对象相等”。JavaScript允许您使用==
比较字符串和数字,但所有其他类型都作为对象进行比较
即:
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
方法获得可比较的数值:
foo = new Date();
bar = new Date(foo);
console.log(foo.getTime() == bar.getTime()); //prints true
尝试使用日期方法valueOf()
比较它们。这将在下面比较它们的基本值,而不是比较日期对象本身
例如:
console.log(prevDate.valueOf()==currDate.valueOf())//应为真
console.log(prevDate.getTime() === currDate.getTime());
(正如nss正确指出的,我现在明白了)
为什么我在这里使用===呢?查看一下不要使用==运算符直接比较对象,因为==仅当两个比较变量都指向同一对象时才会返回true,请先使用object valueOf()函数获取对象值,然后比较它们
i、 e
var prevDate = new Date('1/25/2011');
var currDate = new Date('1/25/2011');
console.log(prevDate == currDate ); //print false
currDate = prevDate;
console.log(prevDate == currDate ); //print true
var currDate = new Date(); //this contain current date i.e 1/25/2011
currDate.setHours(0, 0, 0, 0);
console.log(prevDate == currDate); //print false
console.log(prevDate.valueOf() == currDate.valueOf()); //print true