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

在React Native中使用date-fns格式化Firestore时间戳报错

解决date-fns处理Firestore时间戳时的「Invalid time value」错误

你的问题出在对subDays函数的用法误解上:

  • subDays的第二个参数是要减去的天数(数字类型),不是日期对象。你现在把Firestore时间戳转成的Date对象传给它,导致生成了无效的时间值,触发了错误。
  • formatDistance本身就是用来计算两个日期之间的时间差,不需要额外用subDays处理Firestore的时间戳。

正确代码示例

直接将Firestore时间戳转成的Date对象作为第一个参数(过去的时间),当前时间作为第二个参数传入:

formatDistance(item.created_at.toDate(), new Date(), { addSuffix: true })

额外注意事项

如果item.created_at可能为空或不是有效的Firestore时间戳,建议先做校验,避免报错:

if (item?.created_at) {
  const timeAgo = formatDistance(item.created_at.toDate(), new Date(), { addSuffix: true });
  // 在这里使用timeAgo
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:52:04