【问题标题】:Disable recurring dates using jQuery Calendar使用 jQuery 日历禁用重复日期
【发布时间】:2026-02-19 09:05:03
【问题描述】:

我想使用 jQuery 日历禁用全年的第二个星期六、第四个星期六、星期日和公众假期。

【问题讨论】:

标签: javascript jquery jquery-ui


【解决方案1】:

Jquery 日历插件为你提供了一个选项“beforeShowDay”,你可以 查找有关 DataPickerUI 的更多信息

要禁用第 2 个星期六和第 4 个星期六,您需要先计算特定月份的星期六或星期日,然后禁用这些日期,就像我们对其他日历所做的那样

示例代码计算周六和周日https://www.hscripts.com/scripts/JavaScript/second-fourth.php

为您创建了 plunker, https://plnkr.co/edit/inBYY748BptaCd7Ulwwg?p=preview

                //To disable Sundays you need to find out the Day of current date.
            $(function () {
                var publicHolidays = [
                  [11, 28, 2015],
                  [11, 30, 2015]
                ];

                $("#datepicker").datepicker({
                    beforeShowDay: function (date) {
                        var day = date.getDay();
                        return [(day !== 0), ''];
                    }
                });

                //To disable public holidays create an array with you holiday list then
                //return false when you browse calender.

                $("#datepicker2").datepicker({
                    beforeShowDay: function (date) {
                        for (i = 0; i < publicHolidays.length; i++) {
                            if (date.getMonth() == publicHolidays[i][0] &&
                              date.getDate() == publicHolidays[i][1] &&
                              date.getFullYear() == publicHolidays[i][2]) {
                                return [false];
                            }
                        }
                        return [true];
                    }
                });
            });

【讨论】:

    【解决方案2】:

    对于它的价值,这里有几个函数用于问题的第二个/第四个星期六部分。

    这两个函数都接受 javascript Date() 的实例并返回 truefalse。你可以使用任何一个。

    function is2ndOr4thSat_1(date) {
        var day = date.getDay(),
            week = Math.floor(date.getDate() / 7);
        return day == 6 && (week == 1 || week == 3)
    }
    

    希望is2ndOr4thSat_1() 是不言自明的。

    function is2ndOr4thSat_2(date) {
        var d = date.getDate(),
            offset = (((1 + date.getDay() - d) % 7) + 7) % 7;
        return !((offset + d) % 14);
    }
    

    is2ndOr4thSat_2() 更加晦涩难懂。

    表达式(((1 + date.getDay() - d) % 7) + 7) % 7 使用适合负数的真正模算法查找本月第一天与名义零(第一天的前一个星期六)的偏移量。

    如果 date 比名义零提前 14 或 28 天,则 (offset + d) % 14 返回 0,并且 ! 转换为所需意义的布尔值(true 用于符合条件的星期六,否则 false )。

    【讨论】: