I wanted to have a datepicker that would disable not only past dates, but also future dates. All of the answers on Stack Overflow regarding similar questions all point towards using startDate and endDate. But what if you're using a version of datepicker that doesn't have those options? For example, bootstrap-datepicker.js.
The main obstacle was correctly setting the ending cut-off date (at least for me). I found that the method that should work for all datepickers is to directly add or subtract the date in the date declaration when initializing it, because this is a JS operation and bootstrap datepickers are based on JS:
new Date(checkin.date.getFullYear(), checkin.date.getMonth(), checkin.date.getDate() + 6, 0, 0, 0, 0);
Note how I have the + 6 next to the date as I want the end date to be one week after the chosen start date, and to disable everything after that.
Thus, the full code for disabling everything before and everything one week after the chosen start date is:
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $('.date-group').datepicker({
onRender: function (date) {
}
}).on('changeDate', function (ev) {
//if (ev.date.valueOf() > checkout.date.valueOf()) {
var newDate = new Date(ev.date)
newDate.setDate(newDate.getDate() + 0); // automatic date offset for end date (currently 0)
checkout.setValue(newDate);
//}
checkin.hide();
checkout.show();
$('.end-date-group')[0].focus();
}).data('datepicker');
var checkout = $('.end-date-group').datepicker({
onRender: function (date) {
var cap = new Date(checkin.date.getFullYear(), checkin.date.getMonth(), checkin.date.getDate() + 6, 0, 0, 0, 0);
if (date.valueOf() < checkin.date.valueOf()) {
return 'disabled';
}
else if (date.valueOf() > cap.valueOf()) {
return 'disabled';
}
}
}).on('changeDate', function (ev) {
checkout.hide();
}).data('datepicker');
The resulting datepicker:
You can also do the same for month and year should the need arise.
For reference, the specific datepicker that I used is bootstrap-datepicker.js.
Hopefully this helped. Cheers!