gpt4 book ai didi

javascript - 获取一年中的所有星期一

转载 作者:行者123 更新时间:2023-11-30 09:33:35 25 4
gpt4 key购买 nike

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

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);
}

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

我如何调整此代码以获取一年中所有剩余的星期一?

最佳答案

只需循环年而不是月。代码和你的一样,没问题。刚刚更改了月 -> 年和 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);
}

关于javascript - 获取一年中的所有星期一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44893376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com