【问题标题】:How to sort table data by date?如何按日期对表格数据进行排序?
【发布时间】:2021-04-19 05:38:19
【问题描述】:

这是我的数据表

正如您在表格中看到的,最早的注册日期在最前面,但我希望最新的数据在最前面。

这是我的代码:

this.dataSource = [];
    this.dataSource = this.dataSource.sort((a, b) => {
      if (a.createdAt > b.createdAt) {
          return 1;
        }
      if (a.createdAt < b.createdAt) {
          return -1;
        }
      return 0;

    });

createdAt 是一个字符串

【问题讨论】:

  • createdAt 里面的值是什么?

标签: angular typescript material-table


【解决方案1】:

您的排序代码不正确。正确的排序代码是:

this.dataSource = [];
    this.dataSource = this.dataSource.sort((a, b) => {
      var result = 0;
      if (a.createdAt > b.createdAt) {
          result = 1;
      } else {
          result = -1;
      }
      return result;
    });

【讨论】:

  • @RenceSacramento 请检查 createdAt 变量的格式,因为它是一个字符串,并且比较仅适用于日期格式。
【解决方案2】:

@Rence Sacramento createdAt 将是时间戳或日期字符串。 此外,这将是两个不同的变量“DataSource”和“dataSource”。

this.DataSource = [];  
    this.DataSource = this.dataSource.sort((a, b) => {
      return new Date(a.createdAt) - new Date(b.createdAt); // ASC order by createdAt
    });

【讨论】:

    猜你喜欢
    • 2020-01-15
    • 2016-10-15
    • 1970-01-01
    • 2011-09-08
    • 2019-01-17
    • 2020-06-04
    • 1970-01-01
    • 2021-10-31
    • 2021-01-14
    相关资源
    最近更新 更多