1.1 KiB
1.1 KiB
title, type, tags, cover, dateModified
| title | type | tags | cover | dateModified | |
|---|---|---|---|---|---|
| Count weekdays between two dates | snippet |
|
organizer | 2020-10-20T11:21:07+03:00 |
Counts the weekdays between two dates.
- Use
Array.from()to construct an array withlengthequal to the number of days betweenstartDateandendDate. - Use
Array.prototype.reduce()to iterate over the array, checking if each date is a weekday and incrementingcount. - Update
startDatewith the next day each loop usingDate.prototype.getDate()andDate.prototype.setDate()to advance it by one day. - NOTE: Does not take official holidays into account.
const countWeekDaysBetween = (startDate, endDate) =>
Array
.from({ length: (endDate - startDate) / (1000 * 3600 * 24) })
.reduce(count => {
if (startDate.getDay() % 6 !== 0) count++;
startDate = new Date(startDate.setDate(startDate.getDate() + 1));
return count;
}, 0);
countWeekDaysBetween(new Date('Oct 05, 2020'), new Date('Oct 06, 2020')); // 1
countWeekDaysBetween(new Date('Oct 05, 2020'), new Date('Oct 14, 2020')); // 7