如果设备或模拟器未处于"debug remotely"模式,则获取"INVALID DATE"



我正在应用程序中构建聊天功能,并且正在使用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;
}

谢谢!

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

moment().format()

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

以下是我如何使用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;
},

最新更新