首页 > 解决方案 > 将所有数组对象(firestore 时间戳)转换为日期

问题描述

我正在使用 firestore 和 react-native-gifted-chat,我正在尝试将所有聊天消息从 firestore 获取到聊天。但是,有天赋的聊天不支持显示 Firebase 时间戳。它将显示无效日期。因此,我正在尝试转换所有日期对象。

async _getMessage() {
  const messColRef = db.collection('Message').doc(this.state.roomName).collection('message').orderBy('createdAt', 'desc').limit(9)
  const initialQuery = messColRef
  const documentSnapshots = await initialQuery.get()
  const documentData = documentSnapshots.docs.map(document => ({
    id: document.id, ...document.data()
  }));
  const lastVisible = documentData[documentData.length - 1]

  const finalData = _.forEach(documentData['createdAt'], (item) => {
    return item.toDate()
  });
  console.log(documentData)
}

这就是我的数据的样子:

{
  "_id": "f0feb0b6-c0f9-4735-a93d-4297872a4840",
    "createdAt": Timestamp {
    "nanoseconds": 382000000,
      "seconds": 1568995812,
 },
  "id": "Uw6PNNsf7aqWrxcgSDSi",
    "text": "Hi",
      "user": {
    "_id": "V8h2iSllhPXSr8sTGP0yHiaYZwx1",
      "avatar": "https://firebasestorage.googleapis.com/v0/b/exit-3684f.appspot.com/o/add- 
    user.png ? alt = media & token=395c8beb - 47a3 - 4ae6 - a0a1 - fe901e7ad42f",
    "name": "This is the username",
 },
},
{
  "_id": "cc298d96-f19a-4ec7-bdf7-3767d900a364",
    "createdAt": Timestamp {
    "nanoseconds": 373000000,
      "seconds": 1568995733,
 },
  "id": "WzbOA52Y3qukvPUIXRLB",
    "text": "hello",
      "user": {
    "_id": "V8h2iSllhPXSr8sTGP0yHiaYZwx1",
      "avatar": "https://firebasestorage.googleapis.com/v0/b/exit-3684f.appspot.com/o/add- 
    user.png ? alt = media & token=395c8beb - 47a3 - 4ae6 - a0a1 - fe901e7ad42f",
    "name": "This is the username",
    },
},

所以我的目标是将所有时间转换createdAt为 js 时间日期

标签: javascriptfirebasereact-native

解决方案


使用天才聊天的 renderTime 属性并传递一个转换时间并在字符串中返回该时间的函数。


推荐阅读