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

为何将Firestore Timestamp传入Moment.js会返回无效日期?

解决Moment.js处理Firestore Timestamp返回无效日期的问题

问题原因

Moment.js的构造函数无法直接识别Firestore Timestamp的seconds+nanoseconds结构,直接传入这种格式会导致日期解析失败,返回「invalid date」。

可行解决方案

方法1:转换为毫秒时间戳传入

通过计算将秒数和纳秒数转为标准毫秒时间戳,再传给Moment:

const timestamp = {seconds: 1663679594, nanoseconds: 42000000};
const ms = timestamp.seconds * 1000 + timestamp.nanoseconds / 1000000;
const formattedDate = moment(ms).format('MM-DD-YYYY');

方法2:先转为Date对象

如果是Firestore官方的Timestamp实例,可直接调用toDate()方法;如果是手动模拟的结构,也可以自行创建Date对象:

// 处理Firestore官方Timestamp实例
const firestoreTimestamp = /* 你的Firestore Timestamp实例 */;
const formattedDate = moment(firestoreTimestamp.toDate()).format('MM-DD-YYYY');

// 处理手动定义的{seconds, nanoseconds}对象
const timestamp = {seconds: 1663679594, nanoseconds: 42000000};
const date = new Date(timestamp.seconds * 1000 + timestamp.nanoseconds / 1000000);
const formattedDate = moment(date).format('MM-DD-YYYY');

方法3:利用Moment的unix时间戳API

Moment支持传入unix秒级时间戳,再补充纳秒转换的毫秒偏移:

const timestamp = {seconds: 1663679594, nanoseconds: 42000000};
const formattedDate = moment.unix(timestamp.seconds)
  .add(timestamp.nanoseconds / 1000000, 'ms')
  .format('MM-DD-YYYY');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:25:21