如何使用js获得一个月的四个星期一? [英] How can I get the 4 Mondays of a month with js?

查看:73
本文介绍了如何使用js获得一个月的四个星期一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building a chart where the x-axis should be the four weeks of a month. I would like to display only the four Mondays of that month.

我已经有 currentMonth currentYear 变量,我知道如何获取每月的第一天。我所需要的只是安排一个月中的四个星期一。而且所有这些都在同一个JavaScript文件中。

I already have the currentMonth and the currentYear variables, and I know how to get the first day of the month. All I need is to get the four Mondays of a month in an array. And all of this in the same JavaScript file.

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

I'm pretty lost within my programming logic, and I've seen plenty of solutions that don't fit my use case.

现在,我有:

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

但是我想要这样的东西:

but I would like to have something like this:

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


推荐答案

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

The following function will return all Mondays for the current month:

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

这篇关于如何使用js获得一个月的四个星期一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆