我使用 Moment 解析从 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"
但是上面的代码不起作用。它给了我一个警告:
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format.
moment
construction falls back to jsDate()
, which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
我怎样才能让它发挥作用?
最佳答案
正如其他人所述,格式“DD/MM/YYYY”不是 ISO 8601 格式,生成的字符串可能不明确。
你真的应该使用 Date 或 moment 对象,而不是字符串。
因此,当您将日期存储在数组对象中时,不要调用 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>
关于javascript - 用 moment.js : Deprecation warning: value provided is not in a recognized RFC2822 or ISO format 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48692757/