使用日期选择器选择时间段后,自动计算出工作日天数
节假日和调休日需要考虑到
可以提前设置当年的节假日和调休日,或者设置成接口从后台读取;

<body>
    <div>
        <span>开始</span>
        <label for="start">
            <input type="date" name="start" id="startInput">
        </label>
    </div>
    <div>
        <span>结束</span>
        <label for="end">
            <input type="date" name="end" id="endInput">
        </label>
    </div>
    <div>
        <span>工作日</span>
        <label for="daynum">
            <input type="value" name="daynum" id="dayInput">
        </label>
    </div>
</body>

选择结束日期后自动带出工作日天数
这里使用jquery演示
逻辑:调休日不论周内周末都算工作日,周内非节假日算工作日,其余的直接忽略

<script>
    $("#endInput").change(function () {
        var startVal = $("#startInput").val();
        var endVal = $("#endInput").val();
        var num = getWeekday(startVal, endVal);
        $("#dayInput").val(num);
    })

    // 节假日计算
    function getWeekday(first, last) {
        var Holiday = ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-31', '2022-02-01', '2022-02-02', '2022-02-03',
            '2022-02-04', '2022-02-05', '2022-02-06', '2022-04-03', '2022-04-04', '2022-04-05', '2022-04-30',
            '2022-05-01', '2022-05-02', '2022-05-03', '2022-05-04', '2022-06-03', '2022-06-04', '2022-06-05',
            '2022-09-10', '2022-09-11', '2022-09-12', '2022-10-01', '2022-10-02', '2022-10-03', '2022-10-04',
            '2022-10-05', '2022-10-06', '2022-10-07'
        ];
        var WeekendsOff = ['2022-01-29', '2022-01-30', '2022-04-02', '2022-04-24', '2022-05-07', '2022-10-08',
            '2022-10-09',
        ];
        first = new Date(first).getTime();
        last = new Date(last).getTime();
        var count = 0;
        for (var i = first; i <= last; i += 24 * 3600 * 1000) {
            // 整理时间格式
            var date = new Date(i);
            var seperator1 = "-";
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            var day = date.getDay();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = year + seperator1 + month + seperator1 + strDate;
            if (WeekendsOff.indexOf(currentdate) > -1) {
                // 调休日
                count++;
            } else if (day >= 1 && day <= 5 && Holiday.indexOf(currentdate) == -1) {
                // 周内非节假日
                count++;
            }
        }
        return count;
    }
</script>

最后计算结果


miomiomio
147 声望5 粉丝

人生昧履,砥砺而行