You can use Moment.js along with JavaScript to exclude weekends (Saturdays and Sundays) between two dates.
To do this we:
- Create Moment.js objects for the start and end dates.
- Iterate through the dates between the start and end dates.
- Check if each date falls on a weekend.
- 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.