我用时间解析从API获得的日期,在收集完数据后,我需要对数组进行排序。我现在有这样的情况:
myobject.name = name;
myobject.time = Moment(ajaxinfo.startdate).format('DD/MM/YYYY');
array.push(myobject);
// ... more data is added ...
array.sort((left, right) => {
return Moment.utc(left.time).diff(Moment.utc(right.time));
});ajaxinfo.startdate是我从API获得的字符串,它看起来像"2018-01-28T13:00:00+00:00"。
但上述代码不起作用。它给我一个警告:
弃用警告:提供的值不是以公认的RFC2822或ISO格式提供的。
moment结构可以追溯到jsDate(),它并不是所有浏览器和版本都可靠的。非ISO 2822/ISO日期格式是不鼓励的,并将在即将发布的主要版本中删除。请参考http://momentjs.com/guides/#/warnings/js-date/获得更多信息。
我怎么才能让它起作用?
发布于 2018-02-08 19:13:38
根据警告中到动量文档的链接,浏览器在解析您提供的"DD/MM/YYYY"格式时可能不可靠或不一致。如果您需要保留这种格式,一种解决方案是在计算diff时将字符串转换回某个矩对象时提供该格式。所以你可以做return moment.utc(left.timeStamp, 'DD/MM/YYYY').diff(moment.utc(right.timeStamp, 'DD/MM/YYYY'))
发布于 2018-02-08 19:34:11
正如其他人所指出的,"DD/MM/YYYY“格式不是ISO 8601格式,因此产生的字符串可能是不明确的。
您应该真正地处理日期或时间对象,而不是字符串。
因此,当您在数组对象中存储日期时,不要调用format。如果您需要呈现日期,请在那个时候调用format。
const Moment = moment;
// Sample strings
var ajaxinfos = [
{ name: "x", startdate: "2018-01-28T13:00:00+00:00" },
{ name: "y", startdate: "2018-01-26T18:00:00+00:00" }
];
const array = [];
for (const ajaxinfo of ajaxinfos) {
const myobject = {};
myobject.name = ajaxinfo.name;
myobject.time = Moment(ajaxinfo.startdate); // don't call format
array.push(myobject);
}
// No more need to convert strings to dates while sorting:
array.sort((left, right) => left.time.diff(right.time));
console.log(array);
// Whenever you need to format:
const formatted = array.map(info => info.time.format("MM/DD/YYYY"));
console.log(formatted);.as-console-wrapper { max-height: 100% !important; top: 0; }<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.0/moment.min.js"></script>
https://stackoverflow.com/questions/48692757
复制相似问题