0

我正在应用程序中构建聊天功能,并且正在使用 FaridSafi/react-native-gifted-chat。当我在 chrome 上调试时,消息日期很好。如果我不远程调试所有消息日期变为“无效日期”。我在真实设备和模拟器上有相同的结果

我使用此函数将我从 API 获得的日期格式化为库所采用的格式:

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;
}

谢谢!

4

3 回答 3

1

我使用 Moment.JS 自己解决了这个问题,使用

moment().format()
于 2020-09-14T22:14:16.863 回答
0

请注意,您的“new Date()”参数具有 ISO_8601 格式。有关此的更多信息,请参见此处:https ://stackoverflow.com/a/58353084/1256697

于 2019-10-12T10:19:52.820 回答
0

以下是我使用 moment.js 解决此问题的方法:

 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;
  }

如果你好奇Util.formatDate在做什么:

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;
  },
于 2020-09-15T15:25:44.343 回答