TypeScript 按日期排序不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40248643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:25:33  来源:igfitidea点击:

TypeScript sort by date not working

sortingtypescript

提问by CommonSenseCode

I have an object TaskItemVOwith field dueDatewhich 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.

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

算术运算的右侧必须是“any”、“number”或枚举类型的类型。

算术运算的左侧必须是“any”、“number”或枚举类型。

So what is the correct way of sorting array by date fields in TypeScript?

那么在 TypeScript 中按日期字段对数组进行排序的正确方法是什么?

回答by Nitzan Tomer

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);
    });
}

回答by Phoenix

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);
    });
}

回答by RnDrx

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);
    });
  }