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.