I'm trying to set a date to 7 working days from today's date (excluding weekends and UK public holidays).
- I start by setting the default date to today's date (todaysDate) + 7 days (todayPlusSevenDays)
- Then I count the number of weekend days between todaysDate & todayPlusSevenDays If I find any I add them to todayPlusSevenDays
- Then I check for public holidays and if I find any I also add them
After performing those checks I have now added extra days to my default date - how can I also check if that new range of days contains weekend or public holidays?
For instance, if the default date becomes a weekend or bank holiday it should also add more days (right now it doesn't).
Here is my code so far: https://jsfiddle.net/7yxna052/
function prepopulateDropdown() {
var todaysDate = new Date(),
tempNewDate = new Date(),
todayPlusSevenDays,
numberOfWeekends,
todayPlusSevenDaysPlusWeekends,
currentHour = todaysDate.getHours(),
holidayCount = 0,
weekendDayCount = 0,
ukHolidays = ['2017-05-12','2017-05-29','2017-08-28','2017-12-25','2017-12-26'];
// check if current time < or > 6pm GMT
function setDefaultdDate(){
if(currentHour >= 18){
todayPlusSevenDays = new Date(tempNewDate.setDate(tempNewDate.getDate() + 7));
}
else{
todayPlusSevenDays = new Date(tempNewDate.setDate(tempNewDate.getDate() + 6));
}
}
setDefaultdDate();
// Weekend day count
function calculateWeekendDays(startDate, endDate){
while(startDate < endDate){
startDate.setDate(startDate.getDate() + 1);
if(startDate.getDay() === 0 || startDate.getDay() == 6){
++weekendDayCount ;
}
}
return weekendDayCount;
}
calculateWeekendDays(todaysDate, todayPlusSevenDays);
todayPlusSevenDaysPlusWeekends = new Date(tempNewDate.setDate(tempNewDate.getDate() + weekendDayCount));
// count UK bank holidays within todayPlusSevenDays
function calculateBankHolidays(startDate, endDate){
startDate.setHours(0,0,0,0);
endDate.setHours(0,0,0,0);
for(i=0; i < ukHolidays.length; i++){
ukHolidaysFormated = new Date(ukHolidays[i]).setHours(0,0,0,0);
d = new Date(ukHolidays[i]).getDay();
if (ukHolidaysFormated >= startDate && ukHolidaysFormated <= endDate && !(d == 0 || d == 6)) {
holidayCount++;
}
}
return holidayCount;
}
calculateBankHolidays(todaysDate, todayPlusSevenDaysPlusWeekends);
todayPlusSevenDaysPlusWeekends = new Date(todayPlusSevenDaysPlusWeekends.setDate(todayPlusSevenDaysPlusWeekends.getDate() + holidayCount));
// set date to prepopulate
var today = new Date();
var year = todayPlusSevenDaysPlusWeekends.getFullYear();
var month = '0' + (todayPlusSevenDaysPlusWeekends.getMonth() + 1);
var day = todayPlusSevenDaysPlusWeekends.getDate();
$('.slctDay option').each(function(){
if($(this).val() == day){
$(this).attr('selected','selected');
}
});
$('.slctMonth option').each(function(){
if($(this).val() == month){
$(this).attr('selected','selected');
}
});
$('.slctYear option').each(function(){
if($(this).val() == year){
$(this).attr('selected','selected');
}
});
}