Categories
JavaScript Answers

How to exclude weekends between two dates using Moment.js and JavaScript?

Spread the love

You can use Moment.js along with JavaScript to exclude weekends (Saturdays and Sundays) between two dates.

To do this we:

  1. Create Moment.js objects for the start and end dates.
  2. Iterate through the dates between the start and end dates.
  3. Check if each date falls on a weekend.
  4. Exclude weekends from the list of dates.

Here’s a code example demonstrating this:

const moment = require('moment');

function getWeekdayDates(startDate, endDate) {
    const dates = [];
    let currentDate = moment(startDate);
    const endDateMoment = moment(endDate);

    while (currentDate.isSameOrBefore(endDateMoment)) {
        // Check if the current date is not a Saturday (6) or Sunday (0)
        if (currentDate.day() !== 6 && currentDate.day() !== 0) {
            dates.push(currentDate.clone().toDate()); // Add the date to the array
        }
        // Move to the next day
        currentDate.add(1, 'day');
    }

    return dates;
}

// Example usage:
const startDate = '2024-04-01'; // Start date (YYYY-MM-DD format)
const endDate = '2024-04-15'; // End date (YYYY-MM-DD format)

const weekdayDates = getWeekdayDates(startDate, endDate);
console.log(weekdayDates);

This code will output an array containing dates between startDate and endDate, excluding weekends.

Ensure you have Moment.js installed via npm or include it via a CDN in your HTML file if you’re using it in a browser environment.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *