Javascript 比较函数生成的日期对象和
我试图比较两个日期:Javascript 比较函数生成的日期对象和,javascript,date,datetime,Javascript,Date,Datetime,我试图比较两个日期: var date = new Date('Mon May 11 2000 00:00:00 GMT+0200 (CEST)'); var processedDate = new Date(new Date(date.setHours(23,59,59,999)).setDate(date.getDate() -1)); if (otherDate.getTime() === processedDate.getTime()) { console.log('equal
var date = new Date('Mon May 11 2000 00:00:00 GMT+0200 (CEST)');
var processedDate = new Date(new Date(date.setHours(23,59,59,999)).setDate(date.getDate() -1));
if (otherDate.getTime() === processedDate.getTime()) {
console.log('equal dates');
}
及
console.logging日期提供完全相同的输出,但是,以下语句不能解析为true:
if (otherDate === processedDate) {
console.log('equal dates');
}
看下面的小提琴:
无法比较对象。请尝试以下操作:
if (otherDate.toString() === processedDate.toString()) {
console.log('equal dates');
}
无法比较对象。请改为尝试以下操作:
if (otherDate.toString() === processedDate.toString()) {
console.log('equal dates');
}
简单回答:不能通过相等直接比较对象。详细答案来自: 对象具有唯一的标识,并通过引用进行比较:通过表达式(如构造函数或文本)创建的每个对象都被视为不同于其他所有对象;可以通过相等运算符(==)观察到的事实。该操作符通过引用比较对象:两个对象只有在具有相同标识时才相等。它们的内容是否相同并不重要 但是,您可以使用
Date
方法比较两个日期的毫秒值:
var date = new Date('Mon May 11 2000 00:00:00 GMT+0200 (CEST)');
var processedDate = new Date(new Date(date.setHours(23,59,59,999)).setDate(date.getDate() -1));
if (otherDate.getTime() === processedDate.getTime()) {
console.log('equal dates');
}
简单回答:不能通过相等直接比较对象。详细答案来自: 对象具有唯一的标识,并通过引用进行比较:通过表达式(如构造函数或文本)创建的每个对象都被视为不同于其他所有对象;可以通过相等运算符(==)观察到的事实。该操作符通过引用比较对象:两个对象只有在具有相同标识时才相等。它们的内容是否相同并不重要 但是,您可以使用
Date
方法比较两个日期的毫秒值:
var date = new Date('Mon May 11 2000 00:00:00 GMT+0200 (CEST)');
var processedDate = new Date(new Date(date.setHours(23,59,59,999)).setDate(date.getDate() -1));
if (otherDate.getTime() === processedDate.getTime()) {
console.log('equal dates');
}