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

如何在Angular中将Firestore Timestamp转换为MM/YYYY格式展示?

解决Firestore Timestamp转MM/YYYY格式的方法

Firestore返回的Timestamp对象需要先转换成JavaScript原生Date对象,再进行格式化处理。你可以修改现有代码,在map过程中完成格式转换,具体有两种实现方式:

方式一:手动拼接格式化字符串

直接提取月份和年份,补零后拼接成目标格式:

const date = this.data.map((item) => {
  // 将Firestore Timestamp转为JS Date对象
  const dateObj = item.weightDate.toDate();
  // 月份从0开始,加1后补零为两位数字
  const month = String(dateObj.getMonth() + 1).padStart(2, '0');
  const year = dateObj.getFullYear();
  return `${month}/${year}`;
});

方式二:使用Intl.DateTimeFormat API(推荐)

利用浏览器原生的国际化API,更简洁且支持本地化配置:

const date = this.data.map((item) => {
  const dateObj = item.weightDate.toDate();
  // 指定格式为两位月份+四位年份
  return new Intl.DateTimeFormat('en-US', {
    month: '2-digit',
    year: 'numeric'
  }).format(dateObj);
});

两种方式最终都会生成MM/YYYY格式的日期字符串,直接用于图表渲染即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 22:32:02