How can I get the 4 Mondays of a month with js?

后端 未结 2 2105
一个人的身影
一个人的身影 2020-12-01 11:54

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.

I already have the cur

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 11:59

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

提交回复
热议问题