Comparing two dates using JavaScript not working as expected
本问题已经有最佳答案,请猛点这里访问。
这是我的javascript代码:
1 2 3 4 5 6 7 8 9 10 | 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 |
注意两个日期是相同的,但是使用
我认为你不能用
即:
1 2 3 4 5 6 7 8 9 10 | 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 |
但是,您可以使用
1 2 3 | foo = new Date(); bar = new Date(foo); console.log(foo.getTime() == bar.getTime()); //prints true |
不要使用==运算符直接比较对象,因为只有当两个比较变量都指向同一对象时,==才会返回true,请先使用object valueof()函数获取对象值,然后比较它们即
1 2 3 4 5 6 7 8 9 | 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 |
1 | console.log(prevDate.getTime() === currDate.getTime()); |
(正如NSS正确指出的那样,我现在明白了)为什么我用==这里?在JavaScript比较中使用等于运算符(==vs===)的查找吗?
尝试使用日期方法
例子:
JS使用