1

I've been trying to create a validation for my form. I've been looking around on how to disable weekends in date time picker as well as holidays. I am using this Jquery script from Trentrichardson http://trentrichardson.com/examples/timepicker/

I am sort of new in JS and am about to pull out my hair as I cannot find a way to make this code work:

$(document).ready(function(){
    $('.timepicker').datetimepicker({ beforeShowDay: $.datepicker.noWeekends });

    var natDays = [
    [2, 26, 'ph'], [2, 6, 'ph'], [2, 17, 'ph']
    ];

    function noWeekendsOrHolidays(date) {
        var noWeekend = $.datepicker.noWeekends(date);
        if (noWeekend[0]) {
            return nationalDays(date);
        } else {
            return noWeekend;
        }
    }

    function nationalDays(date) {
        for (i = 0; i < natDays.length; i++) {
            if (date.getMonth() == natDays[i][0] - 1
            && date.getDate() == natDays[i][1]) {
                return [false, natDays[i][2] + '_day'];
            }
        }
        return [true, ''];
    }


});

I found this code yesterday, which is the correct answer(Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?), but I can't get it to work. It doesn't show the holidays but weekends have been disabled(working).

Any ideas?

Community
  • 1
  • 1
Tissue
  • 41
  • 1
  • 10

1 Answers1

0

Checking whether a date is a Saturday or Sunday should not require a separate function:

if (date.getDay() % 6) {
  // date is not a weekend
} else {
  // date is a weekend
}

Checking for public holidays (which can be much more difficult given that dates change from year to year and place to place) can be easy too. Create a list of the dates in a set format (ISO8601 is convenient), then you can just test against current date:

// You may have a function like this already
// d is a javascript Date object
function dateToISO(d) {
  function z(n){return (n<10? '0':'')+n}
  return d.getFullYear() + '-' +
         z(d.getMonth() + 1) + '-' + 
         z(d.getDate());
}

// s is a date string in ISO8601 format
function isPublicHoliday(s) {
  var holidays = '2012-12-25 2012-12-26'; // list holidays
  var m = holidays.match(s);
  return !!(m && m.length);
}

isPublicHoliday(dateToISO(date));  // true for 2012-12-25

Of course you will want to implement the above differently, but it gives you the gist of it. Presumably the date picker returns a date object, or a formatted string that you can test. Testing against a string is very fast and saves a lot of hassle with arrays and functions. Very easy to maintain too, since the dates are quite human readable.

RobG
  • 142,382
  • 31
  • 172
  • 209