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

Next.js中如何将Firebase时间戳转换为本地日期?

解决Firebase时间戳转本地日期出现Invalid Date的问题

你遇到的问题和toLocaleString的用法无关,核心原因是你直接把Firebase的Timestamp对象传给了new Date()——JS原生的Date构造函数无法识别Firebase自定义的Timestamp结构,所以才会返回Invalid Date。

下面给你两种直接可行的解决方式:

方法一:用Timestamp内置的toDate()方法(推荐)

Firebase的Timestamp对象自带toDate()方法,能直接转换成JS原生Date对象,之后再调用toLocaleString就完全正常了。另外建议处理字段为空的情况(比如用户从未登录过,lastLoginAt可能为null):

<Table.Header>
  <Table.Column>Email</Table.Column>
  <Table.Column>Last login</Table.Column>
  <Table.Column>Created</Table.Column>
</Table.Header>
<Table.Body>
  {usersList.map((user, index) => (
    <Table.Row key={index}>
      <Table.Cell>{user.user.email}</Table.Cell>
      <Table.Cell>
        {user.user.lastLoginAt 
          ? user.user.lastLoginAt.toDate().toLocaleString("da-DK", {
              year: "numeric",
              month: "long",
              day: "numeric",
              hour: "2-digit",
              minute: "2-digit",
            })
          : "从未登录"}
      </Table.Cell>
      <Table.Cell>
        {user.user.createdAt.toDate().toLocaleString("da-DK", {
          year: "numeric",
          month: "long",
          day: "numeric",
          hour: "2-digit",
          minute: "2-digit",
        })}
      </Table.Cell>
    </Table.Row>
  ))}
</Table.Body>

方法二:手动提取时间戳秒数转换

如果因特殊场景无法使用toDate(),可以手动提取Timestamp的seconds字段,乘以1000转成JS Date需要的毫秒级时间戳:

// 示例:处理单个时间字段
new Date(user.user.lastLoginAt.seconds * 1000).toLocaleString("da-DK", {
  year: "numeric",
  month: "long",
  day: "numeric",
  hour: "2-digit",
  minute: "2-digit",
})

这种方式会忽略Timestamp的纳秒部分,一般业务场景下精度足够。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 07:48:15