JavaScript公休日跳转问题求助:补班逻辑与网络时间获取
解决方案
一、核心问题拆解与思路
- 获取网络时间:通过请求服务器资源的响应头
Date字段获取标准时间,避免依赖本地设备时间 - 公休日顺延处理:预先定义所有公休日,对每个日期判断是否为周末,自动顺延至下一个工作日,再与当前网络时间对比
二、完整代码实现
async function myFunction() { // 1. 获取网络时间(通过请求目标服务器的响应头) let networkDate; try { // 发送HEAD请求到目标服务器,仅获取响应头 const response = await fetch('http://10.2.3.30:81', { method: 'HEAD' }); const dateStr = response.headers.get('Date'); networkDate = new Date(dateStr); } catch (error) { // 请求失败时降级使用本地时间 networkDate = new Date(); console.warn('获取网络时间失败,使用本地时间'); } // 2. 定义原始公休日列表(格式:[月, 日]) const originalHolidays = [ [1,1], [1,2], [1,9], [2,11], [2,23], [3,21], [4,29], [5,3], [5,4], [5,5], [7,17], [8,11], [9,18], [9,23], [10,9], [11,3], [11,23] ]; // 3. 处理公休日顺延:转换为实际工作日日期 const getActualHolidayDate = (month, day) => { const year = networkDate.getFullYear(); let holiday = new Date(year, month - 1, day); // 月份为0基索引 // 若为周末则顺延至下一个工作日 while (holiday.getDay() === 0 || holiday.getDay() === 6) { holiday.setDate(holiday.getDate() + 1); } return holiday; }; // 生成所有实际生效的公休日日期对象 const actualHolidays = originalHolidays.map(([month, day]) => getActualHolidayDate(month, day)); // 4. 格式化当前网络时间(仅保留年月日,排除时分秒干扰) const currentDate = new Date(networkDate.getFullYear(), networkDate.getMonth(), networkDate.getDate()); // 5. 判断当前日期是否属于公休日 const isHoliday = actualHolidays.some(holiday => { return holiday.getFullYear() === currentDate.getFullYear() && holiday.getMonth() === currentDate.getMonth() && holiday.getDate() === currentDate.getDate(); }); // 6. 执行跳转逻辑 if (isHoliday) { window.location.href = 'http://google.com'; } else { window.location.href = 'http://10.2.3.30:81'; } }
三、关键代码解释
1. 网络时间获取
- 使用
HEAD请求目标服务器,仅获取响应头而非完整资源,更高效 - 从响应头的
Date字段解析服务器端标准时间,彻底避免本地时间篡改的问题 - 增加异常捕获,请求失败时自动降级为本地时间,保证功能不中断
2. 公休日顺延逻辑
- 用数组存储原始公休日,替代冗余的多
if判断,后续修改维护更方便 - 通过循环判断日期是否为周末(
getDay()返回0为周日,6为周六),自动顺延至下一个工作日 - 统一生成实际生效的公休日列表,再与当前日期做对比
3. 日期对比优化
- 将当前时间和公休日都转换为仅保留年月日的日期对象,避免时分秒差异导致的判断错误
四、使用说明
- 代码使用了
async/await语法,现代浏览器均支持,无需额外配置 - 若服务器不允许
HEAD请求,可将请求方法改为GET,功能不受影响 - 若需处理跨年公休日,可在
getActualHolidayDate函数中手动指定年份
内容的提问来源于stack exchange,提问作者tehnze
相关产品推荐
相关产品推荐

