【问题标题】:convert all array object(firestore timestamp) to date将所有数组对象(firestore 时间戳)转换为日期
【发布时间】:2020-01-21 19:38:18
【问题描述】:

我正在使用 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 时间日期

【问题讨论】:

标签: javascript firebase react-native


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    很抱歉没有深入探索,在检查了@Spatz cmets 之后我想出了如何去做

    documentData.forEach(a => {
      var date = a.createdAt.toDate()
      data.push({
        _id: a._id,
        createdAt: date,
        id: a.id,
        text: a.text,
        user: a.user
      })
    })
    

    【讨论】:

    • 我也试过这个,但收到错误无效日期。你能告诉我为什么吗?
    猜你喜欢
    • 2019-05-10
    • 2021-01-18
    • 2018-12-09
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 2020-08-10
    相关资源
    最近更新 更多