Update countWeekDaysBetween.md

This commit is contained in:
Angelos Chalaris
2020-10-11 14:33:23 +03:00
committed by GitHub
parent ad79909c2e
commit 5a6bb0c353

View File

@ -1,27 +1,26 @@
--- ---
title: countWeekDaysBetween title: countWeekDaysBetween
tags: date, intermediate tags: date,array,intermediate
--- ---
Returns the weekdays count between two dates. Returns the weekday count between two dates.
- Takes startDate and endDate as inputs. - Use `Array.from()` to construct an array with `length` equal to the number of days between `startDate` and `endDate`.
- Executes a while loop if startDate is less than endDate and increments count if startDate does not fall on a weekend. - Use `Array.prototype.reduce()` to iterate over the array, checking if each date is a weekday and incrementing `count`.
- Adds one day to startDate in an iteration and the loop exits when startDate becomes equal to endDate. - Update `startDate` with the next day each loop using `Date.getDate()` and `Date.setDate()` to advance it by one day.
```js ```js
const countWeekDaysBetween = (startDate, endDate) => { const countWeekDaysBetween = (startDate, endDate) =>
let count = 0; Array
while (startDate < endDate) { .from({ length: (endDate - startDate) / (1000 * 3600 * 24) })
if (startDate.getDay() !== 0 && startDate.getDay() !== 6) { .reduce(count => {
count++; if (startDate.getDay() % 6 !== 0) count++;
} startDate = new Date(startDate.setDate(startDate.getDate() + 1));
startDate = new Date(startDate.setDate(startDate.getDate() + 1)); return count;
} }, 0);
return count;
}
``` ```
```js ```js
countWeekDaysBetween(new Date("Oct 09, 2020"), new Date("Oct 14, 2020")); // 3 countWeekDaysBetween(new Date('Oct 05, 2020'), new Date('Oct 06, 2020')); // 1
countWeekDaysBetween(new Date('Oct 05, 2020'), new Date('Oct 14, 2020')); // 7
``` ```