You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular实现按月统计日期数量并返回月份+数量数组

Angular 按月统计记录数量实现方案

嘿,我来帮你搞定这个在Angular里按月统计记录数的需求!不用依赖SQL,直接用前端逻辑就能实现,下面给你两种实用的方案,你可以根据自己的场景选择:

方案一:原生 TS/JS 实现(轻量化,无Angular依赖)

这种方法用原生的Intl.DateTimeFormat来处理月份名称,不需要引入Angular的管道,适合在服务、工具类或者纯逻辑代码里使用。

代码示例

// 你的原始日期数组
const dateArray = ["2021-10-06", "2021-10-06", "2021-10-06", "2021-10-06", "2021-9-06", "2021-9-06", "2021-9-06", "2021-9-06", "2021-9-06"];

// 工具函数:获取日期对应的月份全称(支持多语言)
const getMonthFullName = (dateStr: string): string => {
  const date = new Date(dateStr);
  // 这里用中文本地化,要英文的话改成'en-US'
  return new Intl.DateTimeFormat('zh-CN', { month: 'long' }).format(date);
};

// 步骤1:分组统计每个月份的记录数
const monthCountMap = dateArray.reduce((countMap, dateStr) => {
  const monthName = getMonthFullName(dateStr);
  countMap[monthName] = (countMap[monthName] || 0) + 1;
  return countMap;
}, {} as Record<string, number>);

// 步骤2:转换成你需要的「月份名称+数量」数组
// 如果你需要字符串格式的数组
const resultStringArray = Object.entries(monthCountMap).map(([month, count]) => `${month}: ${count}`);
// 如果你需要对象格式的数组(更便于后续渲染使用)
const resultObjectArray = Object.entries(monthCountMap).map(([month, count]) => ({ month, count }));

// 输出结果:
// resultStringArray → ["十月: 4", "九月: 5"]
// resultObjectArray → [{ month: "十月", count: 4 }, { month: "九月", count: 5 }]

说明

  • Intl.DateTimeFormat是浏览器原生支持的API,能自动处理月份的本地化名称,比手动维护月份数组更可靠;
  • reduce方法高效完成分组统计,逻辑清晰易懂。

方案二:用 Angular DatePipe 实现(适配Angular本地化)

如果你的项目已经在使用Angular的本地化配置,或者想统一用Angular的日期处理工具,这个方案更合适。

代码示例(以独立组件为例)

import { Component } from '@angular/core';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'app-month-stats',
  templateUrl: './month-stats.component.html',
  standalone: true,
  providers: [DatePipe] // 独立组件中需要手动提供DatePipe
})
export class MonthStatsComponent {
  // 原始日期数组
  private dateArray = ["2021-10-06", "2021-10-06", "2021-10-06", "2021-10-06", "2021-9-06", "2021-9-06", "2021-9-06", "2021-9-06", "2021-9-06"];
  
  // 最终统计结果数组
  public monthStatsArray: { month: string; count: number }[] = [];

  constructor(private datePipe: DatePipe) {
    this.calculateMonthStats();
  }

  private calculateMonthStats(): void {
    // 分组统计月份数量
    const countMap = this.dateArray.reduce((acc, dateStr) => {
      // 用DatePipe转换为月份全称,'MMMM'表示全称,第三个参数是本地化语言
      const monthName = this.datePipe.transform(dateStr, 'MMMM', 'zh-CN') || '未知月份';
      acc[monthName] = (acc[monthName] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    // 转换为目标数组格式
    this.monthStatsArray = Object.entries(countMap).map(([month, count]) => ({ month, count }));
  }
}

说明

  • 需要在组件或模块中提供DatePipe(独立组件要手动添加到providers数组);
  • 利用Angular的DatePipe可以无缝对接项目的本地化配置,切换语言时月份名称会自动更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 22:12:28