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

Angular Material v15:自定义matDatepickerFilter后可选日期无法选中

自定义MatDatepicker过滤器导致可点击日期无响应的问题解决

你的问题核心在于日期处理逻辑错误,导致过滤器的允许/禁用判断完全偏离预期,进而让可点击日期失去响应。具体问题点和修复方案如下:

问题分析

  1. 无效的日期偏移:getBookedDayFilter中对用户点击的日期做了+1天处理,实际判断的不是当前点击的日期,而是次日,这直接打乱了预订日期的匹配逻辑。
  2. 时间戳精度干扰:日期比较时未统一时间基准,原始getTime()会包含时分秒毫秒信息,可能与预订数据中的日期字符串解析结果存在精度差异,导致判断错误。

修复方案

1. 修正日期传递逻辑

移除不必要的日期偏移,直接将用户点击的原日期传入判断函数。

2. 统一日期比较基准

将所有参与比较的日期转换为当天0点整的时间戳,消除时间部分的干扰。

修改后的代码

tableService代码

public getBookedDayFilter(roomId: number): any {
    return (date: Date | null): boolean => {
      if (!date) {
        return false;
      }
      // 直接传递原日期,移除+1天的错误操作
      return this.dateService.isDateBooked(date, roomId);
    };
  }

dateService代码

public isDateBooked(date: Date, roomId: number): boolean {
    // 将判断日期转为当天0点时间戳,消除时分秒干扰
    const questionedDate = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
    
    for (const booking of this.bookingService.bookings) {
      if (
        booking.room_id === roomId &&
        booking.booking_id !== this.calendarService.selectedBooking?.booking_id
      ) {
        // 统一预订日期的时间基准为当天0点
        const arrivalDate = new Date(booking.arrival_date).setHours(0, 0, 0, 0);
        const departureDate = new Date(booking.departure_date).setHours(0, 0, 0, 0);

        // 根据业务需求调整:若退房当天允许新预订,用<而非<=
        if (arrivalDate <= questionedDate && questionedDate < departureDate) {
          return false; // 日期被占用,禁用选择
        }
      }
    }
    return true; // 日期可用,允许选择
  }

额外校验点

  • 确认booking.arrival_date和booking.departure_date的格式可被new Date()正确解析
  • 根据业务逻辑调整比较条件:如果退房当天允许新预订,保持questionedDate < departureDate;若退房当天不可选,改为questionedDate <= departureDate

内容的提问来源于stack exchange,提问作者PingWinLqD

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 21:45:33