I'm trying to create a method to calculate the total days off.
I have an array that contains the working days:
"workingDays": [1,2,3,4,5],
So I have two dates; a startDate
and an endDate
, and I should count in this range how many days aren't working days (i.e. total days off).
For example, I have a range from 03/15 (today) to 03/21, a total of 7 days.
Today (03/15) is day 2, and it is a working day so I don't have to increment a counter for days off, while for example 03/19 is not a working day (it is number 6) so I have to increment the day off variable.
I have tried to implement the code, but it doesn't work correctly:
const checkDate = (start, end) => {
const workingDays = [1,2,3,4,5]
let dayOff = 0
var currentDate = new Date(start)
while (currentDate <= end) {
workingDays.map((day) => {
console.log('current ', currentDate.getDay(), ' day ', day)
if (currentDate.getDay() !== day) {
dayOff += 1
}
currentDate = currentDate.addDays(1)
})
}
console.log('dayOff ', dayOff)
return dayOff
}
it prints me:
LOG current 2 day 1
LOG current 3 day 2
LOG current 4 day 3
LOG current 5 day 4
LOG current 6 day 5
LOG current 0 day 1
LOG current 1 day 2
LOG current 2 day 3
LOG current 3 day 4
LOG current 4 day 5
LOG dayOff 10
but it is wrong because the result should be 2.
How can I do? Thank you
EDIT.
The function that I use to add a day:
Date.prototype.addDays = function (days) {
var date = new Date(this.valueOf())
date.setDate(date.getDate() + days)
return date
}