admin管理员组

文章数量:1289556

I used react-native-gifted-chat in my app to add chat feature. Currently I am able to send and receive message from firebase properly. But, the problem is that react-native-gifted-chat always displays 12:00 AM of message send time. This is because it not able to convert firebase timestamp into time. Can anyone please help me how can I solve it ?

Here is the how I used GiftedChat ponent :

<GiftedChat
  messages={this.props.messages}
  renderUsernameOnMessage={true}
  onSend={messages => this.onSend(messages)}
  alwaysShowSend={true}
  textInputStyle={stylesposer}
  minComposerHeight={40}
  minInputToolbarHeight={60}
  user={{
    _id: this.props.account ?.user ?.uid,
    name: this.props.account ?.data ?.fullName,
    avatar: this.props.account ?.data ?.avatar
  }}
/>

Below is the code that i used for saving message in firestore :

export const sendMessage = (message, groupId) => {
  return async () => {
    await firestore().collection('groupMessages').doc(groupId).collection('messages').doc(message._id).set(message).catch((e) => {
      throw {message: e.message.replace(`[${e.code}] `, '')}
    });
  }
}

In above code message is gifted chat message which contains properties : _id, text, createdAt and user.

Here is how message is stored in firebase :

When I display message :

I used react-native-gifted-chat in my app to add chat feature. Currently I am able to send and receive message from firebase properly. But, the problem is that react-native-gifted-chat always displays 12:00 AM of message send time. This is because it not able to convert firebase timestamp into time. Can anyone please help me how can I solve it ?

Here is the how I used GiftedChat ponent :

<GiftedChat
  messages={this.props.messages}
  renderUsernameOnMessage={true}
  onSend={messages => this.onSend(messages)}
  alwaysShowSend={true}
  textInputStyle={styles.poser}
  minComposerHeight={40}
  minInputToolbarHeight={60}
  user={{
    _id: this.props.account ?.user ?.uid,
    name: this.props.account ?.data ?.fullName,
    avatar: this.props.account ?.data ?.avatar
  }}
/>

Below is the code that i used for saving message in firestore :

export const sendMessage = (message, groupId) => {
  return async () => {
    await firestore().collection('groupMessages').doc(groupId).collection('messages').doc(message._id).set(message).catch((e) => {
      throw {message: e.message.replace(`[${e.code}] `, '')}
    });
  }
}

In above code message is gifted chat message which contains properties : _id, text, createdAt and user.

Here is how message is stored in firebase :

When I display message :

Share Improve this question edited Dec 7, 2019 at 5:24 Kishan Bharda asked Dec 6, 2019 at 12:53 Kishan BhardaKishan Bharda 5,7004 gold badges35 silver badges60 bronze badges 2
  • How can u save createdAt in ur code? Share it – DevAS Commented Dec 6, 2019 at 15:42
  • I edited the question about how I saved createdAt. – Kishan Bharda Commented Dec 6, 2019 at 18:16
Add a ment  | 

3 Answers 3

Reset to default 4

Finally done with temporary solution. I solve it by rendering time as custom by renderTime props.

<GiftedChat
  ...
  renderTime={(props) => (
    <View style={props.containerStyle}>
      <CText size={10} style={{marginHorizontal: 10, marginBottom: 5}} bold color={props.position === "left" ? 'gray' : 'white'}>
        {`${props.currentMessage.createdAt.toDate().toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })}`}
      </CText>
    </View>
  )}
  ...
  ...
/>

I have converted createdAt to date and then get it in hh:mm AM/PM formate.

Note: This is just workaround solution and may not work if you are storing message and displaying message locally, because GiftedChat generated message field createdAt is pure javascript date object which has no toDate() function so you may get this type of error.

Uncaught TypeError: (intermediate value).toDate is not a function at :1:12

From my personal experience, the easiest method to solve this is to convert createdAt time property into milliseconds before saving the data into firebase using Date.parse() method. As react-native-gifted-chat generate the message object with different time property format i.e. "createdAt": 2020-05-08T06:56:44.698Z. But when this property is saved into firebase it is shown as timestamp there, and when we fetch the data from firebase it returns the property createdAt with different format i.e. "createdAt": {"_nanoseconds": 943000000, "_seconds": 1588921685}. This causes the issue and the app always shows current date and time 12:00 AM. So the simple solution is to change the date format before saving it into firebase as:

const saveMessage = async (message) => {
    const temp = message[0];

    const createdAt = Date.parse(temp.createdAt); //<--- add this line

    const a = await db.add({ ...temp, createdAt });

    //---------your other code--------//
  }

Now your app will show the correct date and time when you'll fetch the data from firebase.

I fix that problem with this idea also can use.

firestore()
      .collection('Messages')
      .where('experienceId', '==', experienceId)
      .orderBy('createdAt', 'desc')
      .get()
      .then(function (querySnapshot) {
        var messagesAll = [];
        querySnapshot.forEach(function (documentSnapshot) {
          messagesAll.push({
            _id: documentSnapshot.data()._id,
            text: documentSnapshot.data().text,
            createdAt: new Date(documentSnapshot.data().createdAt.toDate()),
            user: documentSnapshot.data().user,
          });
        });
        setMessages(messagesAll);
      });

本文标签: javascriptWhy reactnativegiftedchat not displaying time correctly from firebase timestampStack Overflow