I need to create a dropdown for a schedule system that lists the next 7 Mondays, and last 2 Mondays, based on the current date. The current date obviously could be any day of the week, but the list must only show Mondays.
As such, I also need YYYY-MM-DD formats for the values to be recorded, as well as "friendly" display formats to list in the dropdown.
So I need a JavaScript array of work week start dates (Mondays) based on the current date - 7 weeks ahead, and 2 weeks past. I can't find anything quite like this already on SO.
Here's what I've come up with to address this. It does not rely on any dependencies for formatting. It creates two arrays, which can then be used for the dropdown values:
let production_week_choices = []
const today = new Date(); // test with new Date('2022-01-01')
const day = today.getDay() // Today's current day-of-week (0=Sun ... 6=Sat) numerically
var display_format_options = { weekday: 'short', month: 'short', day: 'numeric' };
for (let i = -49; i < 14; i+=7) { // 7 weeks forward, 2 weeks back, increment loop by 7 days
let i_monday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - day + (day === 0 ? -6 : 1) - i); // adjust when day is Sunday
let date_value = i_monday.toISOString().split('T')[0] // provide in YYYY-MM-DD string format
let date_display = i_monday.toLocaleDateString("en-US", display_format_options) // provide in specified format
production_week_choices.push({"Value": date_value, "Display": date_display})
}
console.log(production_week_choices)
Hope someone else finds this useful!