You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MaterializeCSS日期选择器中每年重复禁用指定日期及周末

实现Materialize Datepicker每年重复禁用周末和特定日期

好问题!要实现每年自动重复禁用周末和指定日期,我们可以利用Materialize Datepicker的disable选项支持自定义判断函数的特性——这个函数会在每个日期渲染时被触发,我们只需要在函数里编写逻辑,判断当前日期是否是周末,或者是否属于每年要禁用的固定月日,返回true即可禁用该日期。

具体实现步骤

1. 定义每年要禁用的固定日期列表

先把需要每年禁用的日期整理成「月-日」格式的数组,这样不管年份如何变化,都能匹配对应日期:

// 每年要禁用的特定日期(MM-DD格式)
const annualDisabledDates = ['05-11', '05-21', '05-24'];

2. 编写日期判断函数

这个函数接收一个原生Date对象作为参数,我们在函数里完成两个判断:是否是周末、是否在禁用日期列表中:

function shouldDisableDate(date) {
  // 判断是否是周末:周日(0)、周六(6)
  const dayOfWeek = date.getDay();
  if (dayOfWeek === 0 || dayOfWeek === 6) {
    return true;
  }

  // 将当前日期格式化为 MM-DD 字符串(注意原生getMonth()是0开始,需要+1)
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const currentMMDD = `${month}-${day}`;

  // 判断是否在每年禁用的日期列表中
  return annualDisabledDates.includes(currentMMDD);
}

3. 初始化Datepicker并应用禁用逻辑

把disable选项设置为我们刚才写的函数,同时保留你原来的其他配置:

$('.datepicker').pickadate({
  disable: shouldDisableDate,
  // 可根据需求添加其他配置
  format: 'yyyy-mm-dd',
  selectMonths: true,
  selectYears: 15,
  today: 'Today',
  clear: 'Clear',
  close: 'Close'
});

扩展:每年重复禁用日期范围

如果需要每年重复禁用某个日期范围(比如每年5月11日到5月22日),可以在判断函数里添加额外逻辑:

function shouldDisableDate(date) {
  // 原有的周末判断
  const dayOfWeek = date.getDay();
  if (dayOfWeek === 0 || dayOfWeek === 6) {
    return true;
  }

  // 每年5月11日-5月22日禁用(注意月份是0开始,5月对应4)
  const currentMonth = date.getMonth();
  const currentDay = date.getDate();
  if (currentMonth === 4 && currentDay >= 11 && currentDay <= 22) {
    return true;
  }

  // 原有的特定日期判断
  const month = String(currentMonth + 1).padStart(2, '0');
  const day = String(currentDay).padStart(2, '0');
  const currentMMDD = `${month}-${day}`;
  return annualDisabledDates.includes(currentMMDD);
}

这种方式的优势在于一劳永逸,不用每年手动更新禁用日期列表,函数会自动为每个渲染的日期做判断,完美满足你每年重复禁用的需求。

内容的提问来源于stack exchange,提问作者Daniel Campos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:04:15