gpt4 book ai didi

javascript - 我怎样才能用js获得一个月的4个星期一?

转载 作者:数据小太阳 更新时间:2023-10-29 03:58:49 26 4
gpt4 key购买 nike

我正在构建一个图表,其中 x 轴应该是一个月的四个星期。我只想显示该月的四个星期一。

我已经有了 currentMonthcurrentYear 变量,而且我知道如何获取该月的第一天。我只需要在数组中获取一个月的四个星期一。所有这些都在同一个 JavaScript 文件中。

我完全迷失在我的编程逻辑中,而且我见过很多不适合我的用例的解决方案。

现在,我有:

var date = new Date();
var currentYear = date.getFullYear();
var currentMonth = date.getMonth();
var firstDayofMonth = new Date(currentYear, currentMonth, 1);
var firstWeekDay = firstDayofMonth.getDay();

但我想要这样的东西:

var myDates = [
new Date(firstMonday),
new Date(secondMonday),
new Date(thirdMonday),
new Date(fourthMonday),
];

最佳答案

以下函数将返回当前月份的所有星期一:

function getMondays() {
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) {
mondays.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}

return mondays;
}

关于javascript - 我怎样才能用js获得一个月的4个星期一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9481158/

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