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

请假管理系统中排除周末节假日的日期计算函数BUG求助

问题定位

你的代码核心bug出在最后赋值阶段的days + 1操作上:

  • 循环逻辑本身是正确的:从起始日到结束日逐个遍历,符合条件(非周末、非节假日)的日期会被计入days变量
  • 但最后额外加1的操作,导致所有场景都多算了一天:
    • 起止日期相同时,循环统计1天,加1后变成2天
    • 连续两个工作日的跨度,循环统计2天,加1后变成3天
    • 大跨度时错误被稀释,看起来“正常”,但逻辑本质错误
修复后的代码

直接移除最后的+1,同时优化日期解析的兼容性:

function calc_days() {
    var days = 0;
    const startVal = $('#date_start').val();
    const endVal = $('#date_end').val();
    
    // 同时校验起止日期是否完整输入
    if (startVal && endVal) {
        // 拼接T00:00:00确保跨浏览器日期解析一致
        var start = new Date(startVal + 'T00:00:00');
        var end = new Date(endVal + 'T00:00:00');
        
        var currentDate = new Date(start);
        while (currentDate <= end) {
            var dayOfWeek = currentDate.getDay();
            if (dayOfWeek !== 0 && dayOfWeek !== 6) { // 排除周末
                var isHoliday = false;
                var month = currentDate.getMonth();
                var day = currentDate.getDate();
                
                // 保留原节假日判断逻辑
                if (month === 0 && day === 1) { // 元旦
                    isHoliday = true;
                } else if (month === 0 && day === 11) { // 独立宣言日
                    isHoliday = true;
                } else if (month === 4 && day === 1) { // 劳动节
                    isHoliday = true;
                } else if (month === 7 && (day === 14 || day === 20 || day === 21)) { // 革命相关节日
                    isHoliday = true;
                } else if (month === 8 && day === 1) { // 绿色进军节
                    isHoliday = true;
                } else if (month === 11 && day === 18) { // 独立日
                    isHoliday = true;
                }
                
                if (!isHoliday) {
                    days++;
                }
            }
            currentDate.setDate(currentDate.getDate() + 1);
        }
    }
    
    if ($('#type').val() == 2) {
        $('#leave_days').val('.5');
    } else {
        $('#leave_days').val(days); // 移除错误的+1操作
    }
}
额外优化建议
  • 节假日可维护性:把节假日列表抽成数组,比如const holidays = [[0,1], [0,11], ...],然后用holidays.some(([m,d]) => m === month && d === day)判断,后续新增节假日更方便
  • 空值处理:可以给#leave_days默认赋值0,避免未输入日期时显示空值

内容的提问来源于stack exchange,提问作者Saâd Saielhaq

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:42:54