如何用js获得一个月的4个星期一?

Gae*_*lle 9 javascript date dayofweek

(首先,请原谅我的英语,我是初学者)

让我解释一下情况:

我想使用Google Charts Tool创建图表(尝试一下,它非常有帮助).这部分并不是很难......

问题来自于我有一个特定的图表需要在x轴上一个月的四个星期:我想在屏幕上只显示当前月的四个星期一.

我已经有了currentMonth和currentYear变量,我知道如何获得当月的第一天.我需要的只是如何在阵列中获得一个月的四个星期一.所有这些都在同一个JavaScript文件中.

我在编程逻辑中迷失了很多,而且我已经看到了很多不适合我的解决方案.

那么,我有什么:

var date = new Date();
var currentYear = date.getFullYear();
var currentMonth = date.getMonth();
var firstDayofMonth = new Date(currentYear, currentMonth, 1);
var firstWeekDay = firstDayofMonth.getDay();
Run Code Online (Sandbox Code Playgroud)

我希望有这样的东西:

var myDates = [
    new Date(firstMonday),
    new Date(secondMonday),
    new Date(thirdMonday),
    new Date(fourthMonday),
];
Run Code Online (Sandbox Code Playgroud)

谢谢你的阅读,如果你能帮助我... :)

Gaelle

jab*_*lab 28

以下内容function将返回当月的所有星期一:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 你是弥赛亚,我想让你知道这一点。 (2认同)