You need to enable JavaScript to run this app. 在Angular中如何按日期对JSON数据进行降序排序?
优惠活动
大模型
产品
解决方案
定价
更多

在Angular中如何按日期对JSON数据进行降序排序?

Angular 接口返回JSON按日期降序排序实现方案

前置准备

假设你从API获取到的响应数据为对象数组,单条数据结构参考如下:

// 可根据你的实际业务字段调整
interface BusinessData {
  id: number;
  content: string;
  // 日期字段支持ISO标准字符串/13位毫秒时间戳,字段名可替换为你实际使用的字段
  createTime: string | number;
}

核心实现代码

在你的组件请求接口的回调逻辑中添加排序代码即可:

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

@Component({
  selector: 'app-data-list',
  templateUrl: './data-list.component.html',
})
export class DataListComponent implements OnInit {
  // 存储排序后的结果,直接用来渲染视图即可
  sortedList: BusinessData[] = [];

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    // 替换为你的实际接口地址
    this.http.get<BusinessData[]>('/api/your/data/interface').subscribe(rawData => {
      // 核心逻辑:先拷贝原数组避免修改原始响应,再做降序排序
      this.sortedList = [...rawData].sort((a, b) => {
        // 将日期转成毫秒时间戳做差值比较,*降序为后项减前项*
        return new Date(b.createTime).getTime() - new Date(a.createTime).getTime();
      });
    });
  }
}

特殊场景处理:自定义格式日期

如果你的接口返回的日期为非标准格式(比如DD/MM/YYYY、YYYY年MM月DD日),需要先解析日期再比较,以DD/MM/YYYY格式为例:

this.sortedList = [...rawData].sort((a, b) => {
  // 按分隔符拆分日期,转成数值后构造Date对象
  const [aDay, aMonth, aYear] = (a.createTime as string).split('/').map(Number);
  const [bDay, bMonth, bYear] = (b.createTime as string).split('/').map(Number);
  // 注意Date构造函数的月份参数从0开始,所以要减1
  return new Date(bYear, bMonth - 1, bDay).getTime() - new Date(aYear, aMonth - 1, aDay).getTime();
});

视图渲染示例

在组件模板中直接循环排序后的数组即可:

<ul>
  <li *ngFor="let item of sortedList">
    {{item.content}} - {{item.createTime | date:'yyyy年MM月dd日 HH:mm'}}
  </li>
</ul>

常见注意事项

  • 如果接口返回的是10位秒级时间戳,构造Date时需要乘以1000转为毫秒:new Date(b.createTime * 1000).getTime()
  • 如需升序排序,只需把排序逻辑中的b和a调换位置即可:new Date(a.createTime).getTime() - new Date(b.createTime).getTime()
  • Array.sort()为原地排序方法,使用扩展运算符[...rawData]先做浅拷贝,可以避免修改原始接口返回数据

内容的提问来源于stack exchange,提问作者Kumari Saloni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 00:54:03