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

Angular TypeScript中如何按当前日期过滤已完成预订数据?

解决预订数据筛选无效的问题

你的代码存在两个核心问题导致筛选不生效:

  • filter方法未赋值回变量:Array.filter() 不会修改原数组,而是返回新的筛选后数组,你当前仅调用了filter但未将结果赋值给myres,原数组自然不会变化。
  • 筛选条件逻辑错误:你需要筛选退房日期早于当前日期的预订,应该使用 < 而非 >。

修改后的组件代码如下:

export class UserMybookingComponent implements OnInit {
  myres!: Reservation[]
  myDate = new Date();

  constructor(private reservationService: ReservationService, private datePipe: DatePipe ) { 

  }
  
  ngOnInit() {
    this.mybooking()
   
  }

  mybooking(){
    this.reservationService.mybook().subscribe(
      data => {
        // 直接将筛选后的新数组赋值给myres
        this.myres = data.filter(res => new Date(res.checkout) < this.myDate);
      }
    )
  }
}

额外注意事项

如果后端返回的checkout字段是字符串格式(如ISO标准字符串),new Date(res.checkout)可以正常解析,但如果是自定义日期格式,需要额外处理解析逻辑。若存在时区差异问题,可以改用时间戳进行比较,避免时区影响:

this.myres = data.filter(res => new Date(res.checkout).getTime() < this.myDate.getTime());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 22:10:11