简体   繁体   English

TypeScript 按日期排序不起作用

[英]TypeScript sort by date not working

I have an object TaskItemVO with field dueDate which has the type Date :我有一个对象TaskItemVO ,其字段dueDate的类型为Date

export class TaskItemVO {
    
    public dueDate: Date;
}

I have this method which I call when I try to sort by date but it is not working:我有这个方法,当我尝试按日期排序时调用它,但它不起作用:

public sortByDueDate(): void {
    this.myArray.sort((a: TaskItemVO, b: TaskItemVO) => {
        return a.dueDate - b.dueDate;

    });
}

I get this error in the return line of method:我在方法的返回行中收到此错误:

The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.算术运算的右侧必须是“any”、“number”或枚举类型的类型。

The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.算术运算的左侧必须是“any”、“number”或枚举类型。

So what is the correct way of sorting array by date fields in TypeScript?那么在 TypeScript 中按日期字段对数组进行排序的正确方法是什么?

Try using the Date.getTime() method:尝试使用Date.getTime()方法:

public sortByDueDate(): void {
    this.myArray.sort((a: TaskItemVO, b: TaskItemVO) => {
        return a.dueDate.getTime() - b.dueDate.getTime();

    });
}

^ Above throws error with undefined date so try below: ^ 以上会抛出未定义日期的错误,因此请尝试以下操作:


Edit编辑

If you want to handle undefined:如果要处理未定义:

private getTime(date?: Date) {
    return date != null ? date.getTime() : 0;
}


public sortByDueDate(): void {
    this.myArray.sort((a: TaskItemVO, b: TaskItemVO) => {
        return this.getTime(a.dueDate) - this.getTime(b.dueDate);
    });
}

As possible workaround you can use unary + operator here:作为可能的解决方法,您可以在此处使用一元+运算符:

public sortByDueDate(): void {
    this.myArray.sort((a: TaskItemVO, b: TaskItemVO) => {
        return +new Date(a.dueDate) - +new Date(b.dueDate);
    });
}

If you are running into issues with the accepted answer above.如果您遇到上述已接受答案的问题。 I got it to work by creating a new Date and passing in the date parameter.我通过创建一个新的 Date 并传入 date 参数来让它工作。

  private getTime(date?: Date) {
    return date != null ? new Date(date).getTime() : 0;
  }

  public sortByStartDate(array: myobj[]): myobj[] {
    return array.sort((a: myobj, b: myobj) => {
      return this.getTime(a.startDate) - this.getTime(b.startDate);
    });
  }

I believe it's better to use valueOf我相信最好使用valueOf

public sortByDueDate(): void {
    this.myArray.sort((a: TaskItemVO, b: TaskItemVO) => {
        return a.dueDate.valueOf() - b.dueDate.valueOf();
    });
}

according to docs: /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC.根据文档:/** 返回自 UTC 1970 年 1 月 1 日午夜以来存储的时间值(以毫秒为单位)。 */ */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM