似乎无法更新我的过滤器的起点和终点

问题描述 投票:0回答:1

我试图过滤一个数组,从开始日期到结束日期过滤。我怎么都无法更新开始或结束日期。当我尝试更新它不会改变。

export class AppComponent {
  snapshots = [
    { date: '01-02-2017', roomOccupancyCount: 2869, userCount: 1783, location: 'All' },
    { date: '01-05-2017', roomOccupancyCount: 2769, userCount: 1655, location: 'All' },
    { date: '03-02-2017', roomOccupancyCount: 2025, userCount: 1911, location: 'All' },
    { date: '01-02-2017', roomOccupancyCount: 1278, userCount: 1167, location: 'All' },
    { date: '02-02-2017', roomOccupancyCount: 2028, userCount: 1940, location: 'All' },
    { date: '01-10-2017', roomOccupancyCount: 2113, userCount: 2001, location: 'All' },
    { date: '03-02-2017', roomOccupancyCount: 2654, userCount: 1841, location: 'All' },
    { date: '01-02-2017', roomOccupancyCount: 1264, userCount: 1140, location: 'All' },
    { date: '01-02-2017', roomOccupancyCount: 2918, userCount: 2557, location: 'All' },
    { date: '01-20-2017', roomOccupancyCount: 2160, userCount: 2112, location: 'All' }
  ];
  start = '01-02-2017';
  end = '03-03-2017';


   ngOnInit() { 
    this.snapshots = this.snapshots.filter(m => {
      if ( m.date > this.start && m.date < this.end)
      return m
    })
   }

update(updateForm:NgForm):void {
  console.log(updateForm.value);
}
angular
1个回答
0
投票

有两种方法可以解决您的问题。

  1. 将日期字符串转换为日期对象并比较它们的时间

如果您的格式为“mm-dd-yyyy”,则可以使用new Date(dateString)将日期轻松转换为日期对象。

ngOnInit() {
    let comparableStartDate = new Date(this.start)
    let comparableEndDate = new Date(this.end)
    this.snapshots = this.snapshots.filter(m => {
        let mDate = (new Date(m)).getTime()
        if ( mDate > (new Date(this.start)).getTime() && mDate < (new Date(this.end)).getTime()) {
            return true
        }
    })
}
  1. 转换yyyy-mm-dd格式的日期并将它们作为字符串进行比较。

这是将它们作为字符串进行比较的代码:

ngOnInit() {
    let comparableStartDate = this.start.replace( /(\d{2})-(\d{2})-(\d{4})/, "$3-$1-$2")
    let comparableEndDate = this.end.replace( /(\d{2})-(\d{2})-(\d{4})/, "$3-$1-$2")
    this.snapshots = this.snapshots.filter(m => {
        let mDate = m.replace( /(\d{2})-(\d{2})-(\d{4})/, "$3-$1-$2")
        if ( mDate > comparableStartDate && mDate < comparableEndDate) {
            return true
        }
    })
}
© www.soinside.com 2019 - 2024. All rights reserved.