我想要从当前周到下五个星期一的星期一列表。 我试图在当月获得它。但是,如果日期是该月的最后一天,则应给出该星期一的日期和下一个五个星期一的日期。
这是我尝试的代码。
var Mondays = [];
var month = new Date().getMonth();
while (d.getMonth() === month) {
mondays.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}
return mondays
以上内容将返回当前月份的星期一。 有人可以帮我吗?
谢谢。
答案 0 :(得分:1)
function isDate(type) {
return (/^\[object\s+Date\]$/).test(
Object.prototype.toString.call(type)
);
}
function getAllMondaysFromDate(count, date) {
count = parseInt(count, 10);
count = Number.isNaN(count)
? 1
// prevent negative counts and limit counting to
// approximately 200 years into a given date's future.
: Math.min(Math.max(count, 0), 10436);
// do not mutate the date in case it was provided.
// thanks to RobG for pointing to it.
date = (isDate(date) && new Date(date.getTime())) || new Date();
const listOfMondayDates = [];
const mostRecentMondayDelta = ((date.getDay() + 6) % 7);
date.setDate(date.getDate() - mostRecentMondayDelta);
while (count--) {
date.setDate(date.getDate() + 7);
listOfMondayDates.push(
new Date(date.getTime())
);
}
return listOfMondayDates;
}
// default ...
console.log(
'default ...',
getAllMondaysFromDate()
);
// the next upcoming 5 mondays from today ...
console.log(
'the next upcoming 5 mondays from today ...',
getAllMondaysFromDate(5)
.map(date => date.toString())
);
// the next 3 mondays following the day of two weeks ago ...
console.log(
'the next 3 mondays following the day of two weeks ago ...',
getAllMondaysFromDate(3, new Date(Date.now() - (14 * 24 * 3600000)))
.map(date => date.toString())
);
// proof for not mutating the passed date reference ...
const dateNow = new Date(Date.now());
console.log(
'proof for not mutating the passed date reference ...\n',
'before :: dateNow :',
dateNow
);
console.log(
'invoke with `dateNow`',
getAllMondaysFromDate(dateNow)
);
console.log(
'proof for not mutating the passed date reference ...\n',
'after :: dateNow :',
dateNow
);
.as-console-wrapper { min-height: 100%!important; top: 0; }