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

Laravel中使用Bootstrap Datepicker计算日期差时排除周末及禁用日期

解决方案:计算日期区间有效天数(排除周末与禁用日期)

你的现有代码仅计算了日期的总跨度,未处理周末和禁用日期的排除逻辑。我们可以通过重构脚本,实现精准的有效天数统计:

步骤1:保留原HTML结构

页面代码无需调整,继续使用:

<div class="input-group input-date range">
      <input type="text" class="form-control" id="from" value=""/>
      &nbsp;
      <div class="input-group-addon">to</div>
      &nbsp;
      <input type="text" class="form-control" id="to" value=""/>
</div>
<div class="form-group">
     <label>Number of days</label>
     <input class="form-control" readonly type="text" id="numberdays" name="day">
 </div>

步骤2:重构JavaScript逻辑

我们将添加有效天数计算函数,并统一处理两个日期选择器的变化事件:

<script>
// 存储需要排除的禁用日期(格式:YYYY-MM-DD),可从Laravel后端动态传入
let disabledDates = [];

// 核心函数:计算区间内的有效天数(排除周末和禁用日期)
function countValidDays(startDate, endDate) {
    if (!startDate || !endDate) return 0;
    
    let validCount = 0;
    let current = new Date(startDate);
    const end = new Date(endDate);
    
    // 遍历区间内每一天
    while (current <= end) {
        const weekDay = current.getDay();
        // 排除周末(0=周日,6=周六)
        if (weekDay !== 0 && weekDay !== 6) {
            // 排除禁用日期
            const dateStr = current.toISOString().split('T')[0];
            if (!disabledDates.includes(dateStr)) {
                validCount++;
            }
        }
        // 日期递增一天
        current.setDate(current.getDate() + 1);
    }
    return validCount;
}

// 初始化日期选择器并绑定事件
$(document).ready(function() {
    // 初始化起始日期选择器
    $('#from').datepicker({
        dateFormat: 'mm/dd/yyyy',
        startDate: '-0',
        showOnFocus: true,
        todayHighlight: true,
        autoclose: true,
        daysOfWeekDisabled: '0,6',
        orientation: 'bottom'
    }).on('changeDate', updateDayCount);

    // 初始化结束日期选择器
    $('#to').datepicker({
        dateFormat: 'mm/dd/yyyy',
        startDate: '-0',
        showOnFocus: true,
        todayHighlight: true,
        daysOfWeekDisabled: '0,6',
        autoclose: true,
        orientation: 'bottom'
    }).on('changeDate', updateDayCount);
    
    // 更新有效天数到输入框
    function updateDayCount() {
        const startVal = $('#from').val();
        const endVal = $('#to').val();
        
        if (!startVal || !endVal) {
            $('#numberdays').val('');
            return;
        }
        
        // 解析mm/dd/yyyy格式为Date对象(注意月份从0开始)
        const [startMonth, startDay, startYear] = startVal.split('/');
        const startDate = new Date(startYear, startMonth - 1, startDay);
        
        const [endMonth, endDay, endYear] = endVal.split('/');
        const endDate = new Date(endYear, endMonth - 1, endDay);
        
        const validDays = countValidDays(startDate, endDate);
        $('#numberdays').val(validDays);
    }
    
    // 从Laravel后端传入禁用日期示例(通过Blade模板输出)
    // disabledDates = {!! json_encode($disabledDatesFromDB) !!};
});
</script>

关键细节说明

  • 周末过滤:通过getDay()获取星期值,直接排除周日(0)和周六(6)
  • 禁用日期处理:disabledDates数组可存储自定义排除日期,支持从Laravel后端动态传递(比如数据库中的节假日)
  • 双向监听:同时监听起始和结束日期的变化,确保任意日期修改都能实时更新结果
  • 日期解析:针对mm/dd/yyyy格式做特殊处理,避免Date对象解析错误

Laravel后端传递禁用日期示例

如果需要从后端获取禁用日期,可在Blade模板中直接输出JSON:

<script>
// 假设$disabledDates是控制器传递的日期数组,格式如['2024-05-01', '2024-10-01']
let disabledDates = {!! json_encode($disabledDates) !!};
</script>

内容的提问来源于stack exchange,提问作者Jay-ar Cristobal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:45:40