【问题标题】:Angular how to sort date objects of array? [duplicate]Angular如何对数组的日期对象进行排序? [复制]
【发布时间】:2019-12-27 13:01:33
【问题描述】:

我试图弄清楚如何订购一个包含 Date 对象的数组。

下面是我的数组Appointment[](包含3个对象)

0: {id: 36, appointmentDate: "2019-12-27T10:28:15"}
1: {id: 57, appointmentDate: "2020-01-03T08:29:25"}
2: {id: 58, appointmentDate: "2020-01-15T15:45:19"}

这是我尝试实施但没有奏效的方法 a.appointmentDate.getTime is not a function

if(param === 'a'){
      return value.sort((a, b) => { return a.appointmentDate.getTime() - b.appointmentDate.getTime() });
}

下面说另一种方法也不起作用

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type

  if(param === 'a'){
  return value.sort((a, b) => { return new Date(a.appointmentDate) - new Date(b.appointmentDate});
    }

【问题讨论】:

  • 直接使用字符串排序:a.appointmentDate.localeCompare(b.appointmentDate)。如果要使用 Date 构造函数,请在日期对象前添加 ++new Date(a.appointmentDate)。打字稿不喜欢减去日期和类型强制
  • 第一个抛出错误,因为appointmentDate 是一个字符串而不是Date。第二个错误来自 TypeScript,因为它不允许对 Date 对象进行 - 操作。如果有返回日期数字表示的方法/属性,只需检查 Date 的文档即可。

标签: javascript angular sorting


【解决方案1】:

结合你的两个努力:

if(param === 'a'){
  return value.sort((a, b) => { return new Date(a.appointmentDate).getTime() - new Date(b.appointmentDate).getTime() })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 2013-10-26
    • 1970-01-01
    • 2015-02-25
    • 2020-05-18
    • 1970-01-01
    相关资源
    最近更新 更多