javascripthtmldatetimepickerbootstrap-datepicker

How to disable days of the week by periods?


I'm currently trying to add a date picker (Boostrap datepicker) and disable certain days of the week, like Mondays, to prevent reservations on those days when the office is closed. I found the daysOfWeekDisabled parameter, and it works perfectly, but not specifically for this purpose:

$('#date_return').datepicker({
    language: "es",
    format: 'dd/mm/yyyy',
    autoclose: true,
    todayHighlight: true,
    showMeridian: false,
    startView: 2,
    minView: 2,
    maxView: 1,
    pickerPosition: "bottom-left",
    daysOfWeekDisabled: $scope.daysClosedInLocationOfReturn
});

This setup works as expected, but now I need to make it apply to specific periods. For example, from 12/31/2024 to 12/30/2025, and then another period from 12/31/2025 to 12/30/2026. Additionally, the days might change depending on the period.

I also searched online and found what I hoped would solve my problem:

isInvalidDate: function(date) {
    return date.day() === 0 || date.day() === 6;
}

With this function, I thought I could add more conditions to check additional criteria, like specific years or other conditions. However, it didn’t work as expected—it neither disabled the days of the week nor showed any error message. Is there any way I can block specific days within certain periods?


Solution

  • Not sure if you can hide specific periods with your current date picker.

    However you can do so with Bootstrap Datepicker

    With that you can use beforeShownDay option to implement your custom logic.

    Example:

    $('#date_return').datepicker({
       language: "es",
       format: 'dd/mm/yyyy',
       autoclose: true,
       todayHighlight: true,
       pickerPosition: "bottom-left",
       beforeShowDay: function(date) {
           var day = date.getDay(); // 0 (Sunday) ... 6 (Saturday)
    
           // The periods with the days to disable
           var periods = [
               {
                   start: new Date(2024, 11, 31),
                   end: new Date(2025, 11, 30),
                   daysToDisable: [1] // Mondays
               },
               {
                   start: new Date(2025, 11, 31),
                   end: new Date(2026, 11, 30),
                   daysToDisable: [2, 3] // Tuesdays and Wednesdays
               }
           ];
    
           for (var i = 0; i < periods.length; i++) {
               var period = periods[i];
               if (date >= period.start && date <= period.end) {
                   if (period.daysToDisable.includes(day)) {
                       return false; // Disable this specific date
                   }
               }
           }
           return true; // Enable all other dates
       }
    });