Last active
September 3, 2021 15:25
-
-
Save shansana/5fb25d8bdeac26172d6af7d501bc2eec to your computer and use it in GitHub Desktop.
JavaScript function to get Working days between 2 days without weekends(Saturday,Sunday) and some custom holidays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var getWorkingDays = function(start,endCount,holidays){ | |
var weekdays = []; | |
var current = start; | |
var i = 0; | |
while(i < endCount){ | |
if (!isWeekEnd(current)) { | |
weekdays.push(current); | |
i++; | |
} | |
currentObj = new Date(current); | |
current = currentObj.addDays(1).format(); | |
} | |
function isWeekEnd(date){ | |
dateObj = new Date(date); | |
if (dateObj.getDay() == 6 || dateObj.getDay() == 0) { | |
return true; | |
}else{ | |
if (holidays.contains(date)) { | |
return true; | |
}else{ | |
return false; | |
} | |
} | |
} | |
return weekdays; | |
} | |
// check if weekend | |
isWeekEnd = function(date){ | |
date.getDay(); | |
return (dayOfWeek == 6 || dayOfWeek == 0); | |
} | |
// check if value exist in array | |
Array.prototype.contains = function(obj) { | |
var i = this.length; | |
while (i--) { | |
if (this[i] == obj) { | |
return true; | |
} | |
} | |
return false; | |
} | |
// get next day | |
Date.prototype.addDays = function(days) { | |
var dat = new Date(this.valueOf()) | |
dat.setDate(dat.getDate() + days); | |
return dat; | |
} | |
//format date | |
Date.prototype.format = function() { | |
var mm = this.getMonth() + 1; | |
var dd = this.getDate(); | |
if (mm < 10) { | |
mm = '0' + mm; | |
} | |
if (dd < 10) { | |
dd = '0' + dd; | |
} | |
return this.getFullYear()+'-'+mm+'-'+dd; | |
}; | |
var start = '2016-10-01'; | |
var daysAhead = 20; | |
var holidayList = ['2016-10-15','2016-10-20','2016-10-19','2016-10-18']; | |
var result = getWorkingDays(start,daysAhead,holidayList); | |
result.forEach(function(item,index){ | |
document.getElementById('result').insertAdjacentHTML('beforeend','<span>'+item+'<br>'); | |
}) | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment