-4

I have a jQuery datepicker and I need to do the following:

  • Disable all Sundays between a specific date range

I understand I need to use the beforeShowDay function but cannot seem to get it in place using the other answers and examples on Stack Overflow.

Any help would be great.

Dan

djnetherton
  • 757
  • 1
  • 7
  • 19

1 Answers1

1

If it's a static set of sundays, you can simply use an array with the dates you want to disable [taken from Jquery UI datepicker. Disable array of Dates ]:

var array = ["2013-03-14","2013-03-15","2013-03-16"]

$('input').datepicker({
    beforeShowDay: function(date){
        var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
        return [ array.indexOf(string) == -1 ]
    }
});

If you want to make a dynamic set of sundays, you'll have to create a function to get an array of Sundays from a start date and an end date.

Here is a function to do exactly that:

function addSundaysToArray(fromDate, toDate, datesToDisable){
  fromDate = new Date(fromDate);
  toDate = new Date(toDate);
  while(fromDate < toDate){
      fromDate.setDate(fromDate.getDate() + 1);

      if(fromDate.getDay() === 0){
          var year = fromDate.getFullYear();
          var month = fromDate.getMonth() + 1;
          month = (month + '').length == 1 ? '0' + month : month;
          var day = fromDate.getDate();
          day = (day + '').length == 1 ? '0' + day : day;

          datesToDisable.push(year + "-" + month + "-" + day);
      }
  }
}

Obviously you can use actual date objects here or even milliseconds. Or you can skip the array input to the function and just return an array with the dates.

I chose to represent the dates as yyyy-mm-dd since most of the times humans read these arrays and it's better to have them readable. Of course, if readability is not that important to you, you can just keep the dates in whatever format you prefer.

Community
  • 1
  • 1
Thatkookooguy
  • 6,669
  • 1
  • 29
  • 54
  • This is great! Would there be a way to have a range of dates rather than the static array? Or possible a function to populate the array based on a start and end date? – djnetherton May 20 '15 at 14:45
  • I added a function to my answer to get all Sundays' dates between two dates. Notice that the function gets the dates as yyyy-mm-dd and populates the array with the same format. If that helped, please mark my answer as the 'accepted' answer :-) – Thatkookooguy May 20 '15 at 15:45