How to sort Date/Time column in angular 4 material sort?

前端 未结 5 609
借酒劲吻你
借酒劲吻你 2021-02-13 21:08

I\'m using angular material table and using matSort for sorting. But it\'s not sorting the dates/time column. It takes the datetime column values as strings.

How to sor

5条回答
  •  醉酒成梦
    2021-02-13 21:49

    Expanding on Sagar Kharche's answer, if you are using the sorting function from the material documentation and using moment.js for your dates, this way will work as well.

    sortData(data: Job[]): Job[] {
    if (!this.sort.active || this.sort.direction === '') { return data; }
    
    return data.sort((a, b) => {
      let propertyA: number | Date | string = '';
      let propertyB: number | Date | string = '';
    
      switch (this.jobSort.active) {
        case 'status': [propertyA, propertyB] = [a.status, b.status]; break;
        case 'type': [propertyA, propertyB] = [a.type, b.type]; break;
        case 'time': [propertyA, propertyB] = [new Date(moment(a.time, 'MMM Do LT').toDate()),
        new Date(moment(b.time, 'MMM Do LT').toDate())]; break;
      }
    
      const valueA = isNaN(+propertyA) ? propertyA : +propertyA;
      const valueB = isNaN(+propertyB) ? propertyB : +propertyB;
    
      return (valueA < valueB ? -1 : 1) * (this.jobSort.direction === 'asc' ? 1 : -1);
    });
    }
    

提交回复
热议问题