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

Angular中TypeScript实现时间戳转EEEE, MMMM d格式日期求助

解决Angular中TypeScript内时间戳转指定日期格式的问题

首先得指出你现有代码里的两个关键错误:

  • d.getDate没有加括号调用,所以返回的是函数本身的代码而非日期数值,这就是你看到function getDate() { [native code] }的原因,正确写法是d.getDate()
  • d.getMonth()返回0-11的数字(0对应一月),你直接加1得到的是数字,但完全没处理星期几、月份英文全称的需求

不过不用自己从零写格式化逻辑,Angular其实提供了和DatePipe同逻辑的TypeScript工具函数formatDate,这是最靠谱的方案,和模板里的管道保持一致,还能自动处理locale和格式规则。

步骤1:导入必要依赖

先从@angular/common导入formatDate,如果项目默认locale不是英文,还需要注册英文locale数据:

import { formatDate, registerLocaleData } from '@angular/common';
import localeEn from '@angular/common/locales/en';

// 注册英文locale,确保日期输出为英文格式
registerLocaleData(localeEn);

步骤2:用formatDate处理时间戳

formatDate的参数格式是:formatDate(value: string | number | Date, format: string, locale: string, timezone?: string)

针对你需要的EEEE, MMMM d格式(比如Tuesday, January 25),可以封装成一个工具函数:

// 注意:如果你的start_time是秒级时间戳,需要乘1000转成毫秒;如果本身是毫秒级就去掉*1000
formatLessonDate(timestamp: number): string {
  const dateInMs = timestamp * 1000;
  // 指定格式和英文locale
  return formatDate(dateInMs, 'EEEE, MMMM d', 'en-US');
}

步骤3:修复课程分组逻辑

你原来的嵌套循环会生成大量重复对象,逻辑效率很低,推荐用Array.reduce来做分组,简洁又高效:

// 假设this.lessons是你的课程数组,每个元素包含start_time字段
this.data = Object.values(
  this.lessons.reduce((grouped, lesson) => {
    const dateTitle = this.formatLessonDate(lesson.start_time);
    // 不存在该日期分组则创建,否则将课程加入分组
    if (!grouped[dateTitle]) {
      grouped[dateTitle] = { title: dateTitle, lessons: [] };
    }
    grouped[dateTitle].lessons.push(lesson);
    return grouped;
  }, {} as Record<string, { title: string; lessons: any[] }>)
);

console.log(this.data);

预期输出

这样处理后,你会得到符合需求的结构:

[
  {
    title: "Tuesday, January 25",
    lessons: [/* 当天的课程列表 */]
  },
  {
    title: "Wednesday, January 26",
    lessons: [/* 当天的课程列表 */]
  }
]

补充说明

  • 如果你的start_time已经是毫秒级时间戳,记得去掉*1000的转换
  • 若需要其他语言的日期格式,只需注册对应locale并修改formatDate的第三个参数即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:04:03