Get the next 3 months of Thursdays and output the date into a select

I need to get the dates of the next 3 months of thursdays, and then output those dates into a select input, with the value formatted as dd/mm/yyyy but the choice showing as “Thursday 12th April 2021”, ideally in jQuery, but PHP would be ok also.

<select>
    <option value="08/04/2021">Thursday 8th April 2021</option>
    <option value="15/04/2021">Thursday 15th April 2021</option>
    <option value="22/04/2021">Thursday 22nd April 2021</option>
    etc
    etc
</select>

I found this jsfiddle that gets all the thursdays of the current month, but I need it to be the NEXT 3 months of thursdays, starting from today’s date. (and including today if today is a Thursday).

It would be ok if it’s the next 12 thursdays from today’s date.

Answer

To get the next X months, you could do:

function getNextMonths(num, include_current = false) {

    let current = new Date();
    let months  = [];

    if (include_current) {

        months.push(current);
        num--;
    }

    for (let i = 1; i <= num; i++) {

        let next = new Date();

        next.setDate(1);
        next.setMonth(current.getMonth() + i);

        months.push(next);
    }

    return months;
}

console.log(getNextMonths(3)); // Gives you the next three months

From there, you just need to loop the months & evaluate their days:

function getDayOfWeek(num_week_day, dates) {

    let days = [];

    for (let i = 0; i < dates.length; i++) {

        // Evaluate current month
        
        let current = {

            year: dates[i].getFullYear(),
            month: dates[i].getMonth()
        };

        current.days = new Date(current.year, current.month + 1, 0).getDate();
        
        // Loop & evaluate days 
        
        for (let d = 1; d <= current.days; d++) {

            let date = new Date(current.year, current.month, d);

            if (date.getDay() == num_week_day) {

                days.push(date);
            }
        }
    }

    return days;
}

// Get all Thursdays (4th day of the week) within the next 3 months.
console.log(getDayOfWeek(4, getNextMonths(3))); 

// Get Thursdays within the next 3 months including the current one
console.log(getDayOfWeek(4, getNextMonths(3, true))); 

// Get Thursdays within the next 3 months including the current one...
let thursdays = getDayOfWeek(4, getNextMonths(3, true));

//...but keep only those Thursdays that are in the future  
let today    = new Date();
let filtered = thursdays.filter(function (date) {

    return date.getTime() >= today.getTime();
});

console.log(thursdays, filtered); 

Both functions return an array of Date objects – you might need to format those according to your needs. See this thread for different approaches on how to do that:

As already pointed out in the comments by referencing this thread, you also might want to consider moment.js for JavaScript date operations.