From f3012a3bfb9c10d18644230e360ac21c4ea1af24 Mon Sep 17 00:00:00 2001 From: Nishanth2143 Date: Sun, 11 Oct 2020 14:14:44 +0530 Subject: [PATCH] countWeekDaysBetween --- snippets/countWeekDaysBetween.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 snippets/countWeekDaysBetween.md diff --git a/snippets/countWeekDaysBetween.md b/snippets/countWeekDaysBetween.md new file mode 100644 index 000000000..4730f6198 --- /dev/null +++ b/snippets/countWeekDaysBetween.md @@ -0,0 +1,27 @@ +--- +title: countWeekDaysBetween +tags: date, intermediate +--- + +Returns the weekdays count between two dates. + +- Takes startDate and endDate as inputs. +- Executes a while loop if startDate is less than endDate and increments count if startDate does not fall on a weekend. +- Adds one day to startDate in an iteration and the loop exits when startDate becomes equal to endDate. + +```js +const countWeekDaysBetween = (startDate, endDate) => { + let count = 0; + while (startDate < endDate) { + if (startDate.getDay() !== 0 && startDate.getDay() !== 6) { + count++; + } + startDate = new Date(startDate.setDate(startDate.getDate() + 1)); + } + return count; +} +``` + +```js +countWeekDaysBetween(new Date("Oct 09, 2020"), new Date("Oct 14, 2020")); // 3 +```