1 回答

TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊
這是一種比較使用Date對(duì)象/存儲(chǔ)毫秒時(shí)間戳的兩個(gè)事務(wù)是否發(fā)生在同一周、同一天或同一月的方法。
const x = new Date("2020-09-19 11:55:30");
const y = new Date("2020-09-17 14:12:44");
Date.prototype.getWeekNumber = function() {
? var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
? var dayNum = d.getUTCDay() || 7;
? d.setUTCDate(d.getUTCDate() + 4 - dayNum);
? var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
? return Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
};
function sameMonth(a, b) {
? return a.getFullYear() == b.getFullYear() && a.getMonth() == b.getMonth();
}
function sameDay(a, b) {
? return sameMonth(a, b) && a.getDate() == b.getDate();
}
function sameWeek(a, b) {
? return a.getFullYear() == b.getFullYear() && a.getWeekNumber() == b.getWeekNumber();
}
console.log(x);
console.log(y);
console.log("same month:", sameMonth(x, y));
console.log("same day:", sameDay(x, y));
console.log("same week:", sameWeek(x, y));
添加回答
舉報(bào)