首页  >  问答  >  正文

使用date-fns与Firestore服务器时间戳

我正在尝试使用 https://date-fns.org/ 在 React Native 中格式化我的 Firestore 服务器时间戳

我从文档中找到了这个示例函数

formatDistance(subDays(new Date(), 3), new Date(), { addSuffix: true })

我假设 formatDistance 有两个参数。我计算的日期也是当前日期。 (计算距离)

但是,当使用时:

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

(item.created_at) - 是我的时间戳。

我收到错误:

Invalid time value

P粉035600555P粉035600555186 天前392

全部回复(1)我来回复

  • P粉939473759

    P粉9394737592024-03-31 14:40:55

    对于基于此文档的 subDays,必需的参数是日期 (要更改的日期)和金额(要减去第一个参数的天数)。 subDays 需要第二个参数的数字,但您为其提供了日期。您可以使用不带 subDays 的 formatDistance。

    在您的用例中,这应该足够了。

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

    只要 item.created 的格式正确,这应该可以工作。这是formatDistance 文档

    回复
    0
  • 取消回复