获取一年中的所有星期一

Ton*_*bet 3 javascript date

我总是在计算日期函数时遇到问题

var d = new Date(),
    month = d.getMonth(),
    mondays = [];

d.setDate(1);

// Get the first Monday in the month
while (d.getDay() !== 1) {
    d.setDate(d.getDate() + 1);
}

// Get all the other Mondays in the month
while (d.getMonth() === month) {
    var pushDate = new Date(d.getTime());
    mondays.push(pushDate.getDate() + '-' + (pushDate.getMonth()+1) + '-' + pushDate.getFullYear());
    d.setDate(d.getDate() + 7);
}
Run Code Online (Sandbox Code Playgroud)

我正在使用此函数获取当月的所有星期一。

如何修改此代码以获得一年中所有剩余的星期一?

Jos*_*mez 5

只需遍历年份而不是月份。代码和你的一样,运行正常。刚刚改变了月 -> 年和 getMonth() -> getYear()

var d = new Date(),
    year = d.getYear(),
    mondays = [];

d.setDate(1);

// Get the first Monday in the month
while (d.getDay() !== 1) {
    d.setDate(d.getDate() + 1);
}

// Get all the other Mondays in the month
while (d.getYear() === year) {
    var pushDate = new Date(d.getTime());
    mondays.push(pushDate.getDate() + '-' + (pushDate.getMonth()+1) + '-' + pushDate.getFullYear());
    d.setDate(d.getDate() + 7);
}
Run Code Online (Sandbox Code Playgroud)