JavaScript如何检测指定地区和给定日期是否为节假日
问题根因
你之前的代码不生效是两个原因导致的:
- 你的
region.holidays是对象数组,每个元素是包含date、day属性的对象,Array.includes()是全等匹配,不可能匹配到日期值,需要取出每个元素的date属性做对比。 - 你传入的参数是
Date类型对象,配置里存储的是DD.MM.YYYY格式的字符串,格式不一致无法直接匹配,需要先做格式转换。
实现代码
1. 日期格式转换工具函数
先将输入的Date对象转为和配置一致的DD.MM.YYYY格式字符串:
function formatDate(date) { const day = String(date.getDate()).padStart(2, '0'); const month = String(date.getMonth() + 1).padStart(2, '0'); const year = date.getFullYear(); return `${day}.${month}.${year}`; }
如果需要按UTC时区计算日期,把getDate/getMonth/getFullYear替换为getUTCDate/getUTCMonth/getUTCFullYear即可。
2. 节假日校验函数
function checkIsHoliday(regionName, inputDate) { // 匹配目标地区 const region = regions.find(item => item.name === regionName); if (!region) return false; // 转换日期格式后校验是否在节假日列表中 const targetDate = formatDate(inputDate); return region.holidays.some(holiday => holiday.date === targetDate); }
使用示例
// 校验 Bayern 地区 2022年1月1日是否为节假日 const date1 = new Date(2022, 0, 1); // 注意JS中月份从0开始计数,1月对应0 console.log(checkIsHoliday('Bayern', date1)); // 输出 true // 校验 Bayern 地区 2022年5月5日是否为节假日 const date2 = new Date(2022, 4, 5); console.log(checkIsHoliday('Bayern', date2)); // 输出 false(当前配置中无该节假日)
内容的提问来源于stack exchange,提问作者Rus
相关产品推荐
相关产品推荐

