首页 > 解决方案 > 如何使用两个日期条件对来自我的 API 的响应进行排序,如果我没有一个条件,则数据必须位于第一个索引处

问题描述

我需要根据我的 StartDate 对我的 API 的返回进行排序,但如果我没有 FinalDate,我必须创建一个验证,数据必须出现在我的第一个索引处。

  1. 开始日期:“2004-06-04” 最终日期:“2004-12-17”

  2. 开始日期:“1997-08-21” 最终日期:“1998-02-26”

  3. 开始日期:“1997-08-21”最终日期:未定义

我试图对 StartDate 进行排序。它有效,但我对最终日期的处理

 this.servidorService.getDesignacoes(this.nomeacaoId).subscribe(
          (response) => {
            if (response.length > 0) {
              this.movimentos = response.sort((a, b) => (b.StartDate< a.StartDate? -1 : b.StartDate> a.StartDate? 1 : 0));
              this.setMovimento();
            }
          },

问题是,StartDate 的那种工作,但如果我有两个相等的 StartDate,一个有 FinalDate 和另一个没有 FinalDate,没有最终日期的数据必须放在第一位。

标签: javascriptangularsorting

解决方案


这取决于您拥有的日期的格式。即使您的问题显示了字符串格式的日期,我还是从Javascript Date对象假设开始。因此,假设您的日期是Javascript Date对象,您可以使用该Date:getTime()函数进行比较。

// Depending on the origin of your array, your previously Date objects
// now can be JSON Date strings, so you need to convert them back to 
// Dates (for example, you maybe is receiving the array from a rest API)
b.StartDate = new Date(b.StartDate);
a.StartDate = new Date(a.StartDate);

// To get the array in descending order, the comparison should be
// (just switch a and b with each other to get ascending order)
b.StartDate.getTime() - a.StartDate.getTime()

// first of all, make sure that both FinalDate dates are falsy or truthy 
// at the same time... in this case, you should do a regular comparison of 
// StartDate. After that, when you know that one of them isn't a falsy,
// you can return -1 or 1, depending on what you want (nulls at the end or
// a the start of the array):
!!a.FinalDate === !!b.FinalDate // => assure that both FinalDates are falsy or both are truthy
  ? b.StartDate.getTime() - a.StartDate.getTime() 
  : !a.FinalDate 
    ? -1
    : 1 // b.FinalDate is null, so it should come First

因此,如果您使用Javascript Date来自服务器的常规对象(如果您确定日期是对象而不是字符串,则可以跳过 coercing-to-Date-objects 部分):

this.servidorService.getDesignacoes(this.nomeacaoId).subscribe((response) => {
  if (response.length > 0) {
    this.movimentos = response.sort((a, b) => {
      b.StartDate = new Date(b.StartDate);
      a.StartDate = new Date(a.StartDate);
      return !!a.FinalDate === !!b.FinalDate
          ? b.StartDate.getTime() - a.StartDate.getTime() 
          : !a.FinalDate ? -1 : 1;
    });
    this.setMovimento();
  }
});

使用日期字符串比较

如果您确定您拥有的日期是 ISO 字符串或类似的东西,您可以使用localeCompare()而不是getTime()

this.servidorService.getDesignacoes(this.nomeacaoId).subscribe((response) => {
  if (response.length > 0) {
    this.movimentos = response.sort((a, b) =>
      !!a.FinalDate === !!b.FinalDate
          ? b.StartDate.localeCompare(a.StartDate)
          : !a.FinalDate ? -1 : 1);
    this.setMovimento();
  }
});

使用第 3 方日期库

如果您使用的是 3rd 方库,momentjs或者date-fns您也可以使用他们提供的日期比较函数而不是上述字符串的localeCompare.


推荐阅读