如何在Angular中对带有日期字段的数组JSON对象进行排序 | Typescript示例

274 阅读3分钟

在这个简短的教程中,如何对阵列中的json日期进行排序?

  • 如何在Angular中创建一个Date对象?
  • 如何在Angular中比较两个日期
  • 在Angular中比较两个没有时间的日期

让我们创建一个JSOn对象的数组,其中一个键值是字符串中的日期。

  arrayJson: any = [
    {
      id: 1,
      name: "john",
      lastModified: '2011-01-01 02:00:00'
    },
    {
      id: 2,
      name: "Franc",
      lastModified: '2001-01-01 02:00:00'
    },
    {
      id: 3,
      name: "Andrew",
      lastModified: '2021-01-01 02:00:00'
    },
    {
      id: 11,
      name: "Mark",
      lastModified: '2020-01-01 02:00:00'
    },
    {
      id: 12,
      name: "Eric",
      lastModified: '2020-02-01 02:00:00'
    },
    {
      id: 8,
      name: "Tony",
      lastModified: '1990-01-01 02:00:00'
    }
  ]

在Angular中对带有日期键的JSON对象数组进行排序

让我们创建一个Angular应用程序并创建一个新的组件array-json-dates.component。

数组排序方法将数组按升序或降序排序。

Angular typescript组件

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-array-json-dates',
  templateUrl: './array-json-dates.component.html',
  styleUrls: ['./array-json-dates.component.scss']
})
export class ArrayJsonDatesComponent implements OnInit {
  arrayJson: any = [
    {
      id: 1,
      name: "john",
      lastModified: '2011-01-01 02:00:00'
    },
    {
      id: 2,
      name: "Franc",
      lastModified: '2001-01-01 02:00:00'
    },
    {
      id: 3,
      name: "Andrew",
      lastModified: '2021-01-01 02:00:00'
    },
    {
      id: 11,
      name: "Mark",
      lastModified: '2020-01-01 02:00:00'
    },
    {
      id: 12,
      name: "Eric",
      lastModified: '2020-02-01 02:00:00'
    },
    {
      id: 8,
      name: "Tony",
      lastModified: '1990-01-01 02:00:00'
    }
  ]
  constructor() { }

  ngOnInit(): void {

  }
  get sortByLastModifiedDesc() {
    return this.arrayJson.sort((a: any, b: any) => {
      return <any>new Date(b.lastModified) - <any>new Date(a.lastModified);
    });
  }
  get sortByLastModifiedAsend() {
    return this.arrayJson.sort((a: any, b: any) => {
      return <any>new Date(b.lastModified) - <any>new Date(a.lastModified);
    });
  }
}

这里是html组件。

<p>Sort Array of JSOn objects with date string key</p>
<ul>
    <li *ngFor="let obj of sortByLastModifiedDesc">{{obj.lastModified}}</li>
</ul>

如何在Angular中用时间戳对一个对象数组进行排序

在Angular中,任何对象都可以使用关系运算符(===)进行比较。同样,我们可以使用===运算符来比较对象。

Angular typescript组件

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-datecompare',
  templateUrl: './datecompare.component.html',
  styleUrls: ['./datecompare.component.css']
})
export class DatecompareComponent implements OnInit {
  date1: Date = new Date();
  date2: Date = new Date();
  constructor() { }

  ngOnInit(): void {

  }
  isDateEqual() {
    if (this.date1.getTime() === this.date2.getTime())
      return true;
    return false;
  }

}

在Typescript中,我们已经编写了检查日期比较的函数isDateEqual()

首先,在Angular中使用一个新的Date对象来创建当前日期。直接Date 对象不能进行比较,相反,我们必须使用Date.getTime 函数和=== 操作符。

模板组件

<p>Date object Comparision</p>
{{isDateEqual()}}  // true

我们还可以使用其他的关系运算符。

如何在Angular中比较给定日期和当前日期

假设日期对象来自数据库,你想将其与当前日期进行比较。

下面是一个Angular的例子,比较给定日期是在当前日期之前还是之后。

我们可以使用<,> !==,<=,>=关系运算符来比较日期。

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-datecompare',
  templateUrl: './datecompare.component.html',
  styleUrls: ['./datecompare.component.css']
})
export class DateComponent implements OnInit {
  date1: Date = new Date('01.01.2020');
  currentDate: Date = new Date();

  constructor() { }

  ngOnInit(): void {

  }

  compareDates(){
    if(this.date1.getTime()<this.currentDate.getTime()){
      console.log("date1 is before current date")
    }
    if(this.date1.getTime()>this.currentDate.getTime()){
      console.log("date1 is after current date")
    }
  }
}

如何在一个模板组件中比较未来日期和当前日期

有时,我们想比较当前日期和未来日期。

这里有一个Angular组件来比较未来日期和给定日期。

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-datecompare',
  templateUrl: './datecompare.component.html',
  styleUrls: ['./datecompare.component.css']
})
export class DateComponent implements OnInit {
  futureDate: Date = new Date('01.01.2022');
  currentDate: Date = new Date();

  constructor() { }

  ngOnInit(): void {

  }

  checkFutureDate(){
    if(this.futureDate.getTime()>this.currentDate.getTime()){
      console.log("date1 is before current date");
      return true;
    }

  }
}

在模板组件中使用*ngIf directive ,我们可以使用函数来检查真实的值

错误 TS7006。参数'a'隐含有'any'类型。

 get sortByLastModified() {
    return this.arrayJson.sort((a, b) => {
      return <any>new Date(b.lastModified) - <any>new Date(a.lastModified);
    });
  }

结论

学习不同的例子来比较两个相等的日期,以及比较未来和给定的日期与当前日期。