Search code examples
javascriptdatedayofweek

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


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 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.

Right now, I have:

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),
];

Solution

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