如何在使用dayjs的Material UI DatePicker中禁用荷兰公共假期
@material-ui/picker 荷兰公共假期禁用实现方案
核心逻辑
Material UI DatePicker 通过 shouldDisableDate 回调属性自定义禁用日期,我们只需要先计算出目标年份的所有荷兰官方公共/银行假期集合,再在回调中判断当前日期是否属于假期集合即可。
具体实现步骤
1. 实现荷兰公共假期计算工具
首先基于高斯复活节算法实现浮动假期计算,结合固定假期规则,生成指定年份的所有假期列表:
import dayjs from 'dayjs'; // 高斯算法计算某年复活节日期 const getEasterDate = (year) => { const a = year % 19; const b = Math.floor(year / 100); const c = year % 100; const d = Math.floor(b / 4); const e = b % 4; const f = Math.floor((b + 8) / 25); const g = Math.floor((b - f + 1) / 3); const h = (19 * a + b - d - g + 15) % 30; const i = Math.floor(c / 4); const k = c % 4; const l = (32 + 2 * e + 2 * i - h - k) % 7; const m = Math.floor((a + 11 * h + 22 * l) / 451); const month = Math.floor((h + l - 7 * m + 114) / 31); const day = ((h + l - 7 * m + 114) % 31) + 1; return dayjs(new Date(year, month - 1, day)); }; // 获取指定年份的所有荷兰公共假期 const getDutchHolidays = (year) => { const holidays = []; // 固定假期 holidays.push(dayjs(new Date(year, 0, 1))); // 元旦 // 国王节 4月27日,周日则提前到26日 const kingDay = dayjs(new Date(year, 3, 27)); holidays.push(kingDay.day() === 0 ? kingDay.subtract(1, 'day') : kingDay); holidays.push(dayjs(new Date(year, 11, 25))); // 圣诞节 holidays.push(dayjs(new Date(year, 11, 26))); // 节礼日 // 浮动假期(基于复活节) const easter = getEasterDate(year); holidays.push(easter); // 复活节 holidays.push(easter.add(1, 'day')); // 复活节后星期一 holidays.push(easter.add(39, 'day')); // 耶稣升天节 holidays.push(easter.add(49, 'day')); // 圣灵降临节 holidays.push(easter.add(50, 'day')); // 圣灵降临节后星期一 // 格式化日期为YYYY-MM-DD统一判断,避免时间戳误差 return holidays.map(item => item.format('YYYY-MM-DD')); };
2. 接入DatePicker禁用逻辑
给DatePicker组件添加shouldDisableDate属性,判断当前日期是否在假期列表中:
import nl from 'dayjs/locale/nl'; import DayjsUtils from '@date-io/dayjs'; // 组件内逻辑 const currentYear = dayjs().year(); // 可根据需要生成前后多年的假期,比如前后10年避免用户切换年份时失效 const dutchHolidays = [ ...getDutchHolidays(currentYear - 10), ...getDutchHolidays(currentYear), ...getDutchHolidays(currentYear + 10) ]; const shouldDisableDate = (date) => { // date是dayjs实例,格式化后判断是否在假期列表中 return dutchHolidays.includes(date.format('YYYY-MM-DD')); }; // 渲染代码 <MuiPickersUtilsProvider utils={DayjsUtils} locale={nl}> <DatePicker shouldDisableDate={shouldDisableDate} // 你原来的其他属性配置 /> </MuiPickersUtilsProvider>
注:你原代码中的
MateriaUIPicker为拼写简写,实际完整引入为MuiPickersUtilsProvider,如果你的项目中已经做了别名配置可保持原有写法。
内容的提问来源于stack exchange,提问作者Alison
相关产品推荐
相关产品推荐

