0

I'm building chat fonctionality in an app and i'm using FaridSafi/react-native-gifted-chat. When i debug on chrome the messages dates are good. if i'm not debugging remotely all dates of messages become "INVALID DATE". I have same result on real device and emulator

I format date i get from the API to the format the library is in using this function:

formatOneMessage(message) {
  const receiver = this.props.navigation.getParam("receiver");
  const receiverName = receiver.Name;
  const receiverLastName = receiver.lastName;
  const formatedDate = Util.formatDate(message.creation_date)
  const FormatedMessage = {
    _id: message.id,
    text: message.content,
    createdAt: new Date(formatedDate),
    user: {
      _id: message.sender_id,
      name: receiverName + " " + receiverLastName,
      avatar: "https://placeimg.com/140/140/any"
    }
  };
  return FormatedMessage;
}
formatDate(date){
  let dateAndTimeArray = date.split(" ");
  let dateArray = dateAndTimeArray[0].split("-");
  let newDate = dateArray[1] + "-" + dateArray[0] + "-" + dateArray[2];
  let newDateAndTime = newDate + " " + dateAndTimeArray[1]
  return newDateAndTime;
}

Thanks!

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
B. Mohammad
  • 2,152
  • 1
  • 13
  • 28

3 Answers3

1

I used Moment.JS to fix this issue myself, using the

moment().format()
Tomo
  • 25
  • 5
0

Be aware, that your Parameter for "new Date()" has ISO_8601 Format. More information about this see here: https://stackoverflow.com/a/58353084/1256697

suther
  • 12,600
  • 4
  • 62
  • 99
0

Here is how i used moment.js to resolve this issue:

 formatOneMessage(message) {
    const receiverName = this.props.navigation.getParam("receiverName");
    const modifiedDate = Util.formatDate(message.creation_date);
    const formatedDate = moment(modifiedDate, "MM-DD-YYYY HH:mm:ss");

    const FormatedMessage = {
      _id: message.id,
      text: message.content,
      createdAt: formatedDate,
      user: {
        _id: message.sender_id,
        name: receiverName,
        avatar: "https://placeimg.com/140/140/any"
      }
    };

    return FormatedMessage;
  }

if you are curious what Util.formatDate is doing:

formatDate(date) {
    let dateAndTimeArray = date.split(" ");
    let dateArray = dateAndTimeArray[0].split("-");
    let newDate = dateArray[1] + "-" + dateArray[0] + "-" + dateArray[2];
    let newDateAndTime = newDate + " " + dateAndTimeArray[1];

    return newDateAndTime;
  },
B. Mohammad
  • 2,152
  • 1
  • 13
  • 28