Checking if two Dates have the same date info

如何检查两个不同的日期对象是否具有相同的日期信息(具有相同的日期、月份、年份... ...) ?我试过“ = =”,“ = = =”和。平等,但似乎没有工作。

121393 次浏览

Hellnar,

您可以尝试(原谅函数名:)-根据 Felix 的 value 修改,而不是 getTime)

function isEqual(startDate, endDate) {
return endDate.valueOf() == startDate.valueOf();
}

用途:

if(isEqual(date1, date2)){
// do something
}

也许能帮到你。

参见:

Http://www.java2s.com/tutorial/javascript/0240__date/datevalueof.htm

你可以使用 valueOf()getTime():

a = new Date(1995,11,17);
b = new Date(1995,11,17);


a.getTime() === b.getTime() // prints true

减去它们,然后比较为零:

var date1 = new Date();
var date2 = new Date();

对日期做点什么..。

(date1 - date2) ? alert("not equal") : alert("equal");

把它放入一个变量:

var datesAreSame = !(date1 - date2);

我用了这个代码:

Date.prototype.isSameDateAs = function(pDate) {
return (
this.getFullYear() === pDate.getFullYear() &&
this.getMonth() === pDate.getMonth() &&
this.getDate() === pDate.getDate()
);
}

然后你就可以这样称呼它: if (aDate.isSameDateAs(otherDate)) { ... }

类型转换为整数:

a = new Date(1995,11,17);
b = new Date(1995,11,17);
+a === +b;  //true

If you are only interested in checking if dates occur on the same day regardless of time then you can use the toDateString() method to compare. This method returns only the date without time:

var start = new Date('2015-01-28T10:00:00Z');
var end = new Date('2015-01-28T18:00:00Z');


if (start.toDateString() === end.toDateString()) {
// Same day - maybe different times
} else {
// Different day
}

确定两个日期是否相等的一个简单的单行替代方法,忽略时间部分:

function isSameDate(a, b) {
return Math.abs(a - b) < (1000 * 3600 * 24) && a.getDay() === b.getDay();
}

它确定日期 a 和 b 的差异是否不超过一天,并共享一周中的同一天。

function isSameDate(a, b) {
return Math.abs(a - b) < (1000 * 3600 * 24) && a.getDay() === b.getDay();
}


console.log(isSameDate(new Date(2017, 7, 21), new Date(2017, 7, 21))); //exact same date => true
console.log(isSameDate(new Date(2017, 7, 21, 23, 59, 59), new Date(2017, 7, 21))); //furthest same dates => true
console.log(isSameDate(new Date(2017, 7, 20, 23, 59, 59), new Date(2017, 7, 21))); //nearest different dates => false
console.log(isSameDate(new Date(2016, 7, 21), new Date(2017, 7, 21))); //different year => false
console.log(isSameDate(new Date(2017, 8, 21), new Date(2017, 7, 21))); //different month => false

为了更好的日期支持使用 等一下 JS是一样的方法

var starDate = moment('2018-03-06').startOf('day');
var endDate  = moment('2018-04-06').startOf('day');


console.log(starDate.isSame(endDate)); // false ( month is different )


var starDate = moment('2018-03-06').startOf('day');
var endDate  = moment('2018-03-06').startOf('day');


console.log(starDate.isSame(endDate)); // true ( year, month and day are the same )

我喜欢用这个密码

function isEqualDate(d1, d2) {
return (
d1.toISOString().startsWith(d2.toISOString().substring(0,10))
);
}


console.log(isEqualDate(new Date(2022,2,2,10,57), new Date(2022,2,2,11,57)) )


console.log(isEqualDate(new Date(), new Date(2022,2,2)) )


console.log(isEqualDate(new Date(), new Date()) )