First, check date not in disabledDates
before setDate to datepicker.
Simply check date not in disabledDates
by format date
to string format 'yyyy-mm-dd' (https://stackoverflow.com/a/3552493/9002484) and use include funtion to check like this.
dtf = new Intl.DateTimeFormat('en', { year: 'numeric', month: '2-digit', day: '2-digit' })
let [{ value: mo },,{ value: da },,{ value: ye }] = dtf.formatToParts(date)
let formatedDate = `${ye}-${mo}-${da}`
if(!disabledDates.includes(formatedDate)){
// not include in disabledDates; so assign date
}else{
// include in disabledDates; do nothing
}
then loop until the selected date not include in disabledDates
$('.next-day').on("click", function() {
var date = $('#picker').datepicker('getDate');
while (true) {
date.setTime(date.getTime() + (1000 * 60 * 60 * 24))
dtf = new Intl.DateTimeFormat('en', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
})
let [{
value: mo
}, , {
value: da
}, , {
value: ye
}] = dtf.formatToParts(date)
let formatedDate = `${ye}-${mo}-${da}`
if (!disabledDates.includes(formatedDate)) {
break;
}
}
$('#picker').datepicker("setDate", date);
});
You can make function that find next date that not in disabledDates
and the code will be like this.
function findNextDateBySkipedDate(startDate, operation, skipedDates) {
let date = new Date(startDate.getTime()); // copy date to new object
while (true) {
if (operation === "+") {
date.setTime(date.getTime() + (1000 * 60 * 60 * 24))
} else if (operation === "-") {
date.setTime(date.getTime() - (1000 * 60 * 60 * 24))
} else {
break;
}
dtf = new Intl.DateTimeFormat('en', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
})
let [{
value: mo
}, , {
value: da
}, , {
value: ye
}] = dtf.formatToParts(date)
let formatedDate = `${ye}-${mo}-${da}`
if (!skipedDates.includes(formatedDate)) {
break;
}
}
return date;
}
$('.next-day').on("click", function() {
var date = $('#picker').datepicker('getDate');
$('#picker').datepicker("setDate", findNextDateBySkipedDate(date, "+", disabledDates));
});
$('.prev-day').on("click", function() {
var date = $('#picker').datepicker('getDate');
$('#picker').datepicker("setDate", findNextDateBySkipedDate(date, "-", disabledDates));
});