Sal*_*n A 2 javascript comparison datetime date
这是我的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
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
Run Code Online (Sandbox Code Playgroud)
请注意,两个日期都相同,但比较使用==表明它们不相同.为什么?
我不认为你可以==用来比较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
Run Code Online (Sandbox Code Playgroud)
但是,您可以使用该getTime方法获取可比较的数值:
foo = new Date();
bar = new Date(foo);
console.log(foo.getTime() == bar.getTime()); //prints true
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11210 次 |
| 最近记录: |