首頁  >  問答  >  主體

使用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 天前394

全部回覆(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
  • 取消回覆