How to Add Date Range to Array in JavaScript (Exclude Weekends)

Problem:

You need to add a range of dates to an array in JavaScript. Sometimes, you may want to exclude weekends (Saturdays and Sundays) from the date range, making it necessary to have a flexible function to handle these cases.

Solution:

You can solve this problem by creating a function that calculates all dates between a start and end date and adds them to an array. The solution also includes an option to skip weekends.

Step-by-Step Solution:

Here’s the JavaScript code that handles both adding a range of dates and optionally ignoring weekends.

function addDateRange(startDate, endDate, allowedDates, ignoreWeekends = false) {
const start = new Date(startDate);
const end = new Date(endDate);

// Loop through each date in the range
while (start <= end) {
const dayOfWeek = start.getDay(); // 0 is Sunday, 6 is Saturday

// Skip Saturdays and Sundays if ignoreWeekends is true
if (ignoreWeekends && (dayOfWeek === 0 || dayOfWeek === 6)) {
start.setDate(start.getDate() + 1);
continue;
}

// Format and add the date to the array
let formattedDate = start.toISOString().split('T')[0];
if (!allowedDates.includes(formattedDate)) {
allowedDates.push(formattedDate);
}

// Increment date by one day
start.setDate(start.getDate() + 1);
}
}

// Example usage:
var allowed_dates = ['2024-10-07', '2024-10-08', '2024-10-09'];
addDateRange('2024-10-07', '2024-11-24', allowed_dates, true); // Exclude weekends

console.log(allowed_dates);

 

How it Works:

  1. Parameters:
    • startDate: The beginning of your date range.
    • endDate: The last date in your range.
    • allowedDates: The array to store dates.
    • ignoreWeekends: Optional boolean to skip weekends.
  2. Functionality:
    The function increments each date from the start date to the end date. If ignoreWeekends is set to true, it skips Saturdays (6) and Sundays (0).

Use Case:

You can use this function to manage events, bookings, or tasks where you need to track or work with dates, and you may need to exclude weekends.

Related Blog

Sign up for our newsletter to stay up to
date with tech news!