使用moment.js排序:弃用警告:提供的值不是可识别的RFC2822或ISO格式 [英] Sort with moment.js: Deprecation warning: value provided is not in a recognized RFC2822 or ISO format
问题描述
我解析了从带有Moment的API获得的日期,我需要在收集数据时对数组进行排序。我目前有这个:
myobject.name = name;
myobject.time = Moment(ajaxinfo.startdate).format('DD / MM / YYYY');
array.push(myobject);
// ...添加更多数据...
array.sort((左,右)=> {
返回Moment.utc(left.time).diff(时刻) .utc(right.time));
});
ajaxinfo.startdate
是一个字符串,我从API获取,它看起来像2018-01-28T13:00:00 + 00:00
<但是上面的代码不起作用。它给了我一个警告:
弃用警告:提供的值不是公认的RFC2822或ISO格式。
时刻
构造回落到jsDate()
,这在所有浏览器和版本中都不可靠。不鼓励使用非RFC2822 / ISO日期格式,并将在即将发布的主要版本中删除。请参阅 http://momentjs.com/guides/#/warnings/js-日期/ 了解更多信息。
如何才能使其有效?
根据警告中指向momentjs文档的链接,浏览器在解析格式时可能不可靠或不一致提供DD / MM / YYYY
。如果需要保留这种格式,一种解决方案是在计算 diff
时将字符串转换回moment对象时提供格式。所以你可以做
返回moment.utc(left.timeStamp,'DD / MM / YYYY')。diff(moment.utc(right.timeStamp,'DD / MM / YYYY') )
I parse dates I get from an API with Moment, and I need to sort the array when I'm done collecting the data. I currently have this:
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
is a string that I get from an API, and it looks like "2018-01-28T13:00:00+00:00"
But the above code doesn't work. It gives me a warning:
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.
How can I make it work?
Based on the link to the momentjs docs in the warning, browsers may be unreliable or inconsistent in parsing the format you're providing "DD/MM/YYYY"
. If you need to keep this format, one solution would be to provide the format when converting the string back to a moment object when calculating the diff
. So you could do
return moment.utc(left.timeStamp, 'DD/MM/YYYY').diff(moment.utc(right.timeStamp, 'DD/MM/YYYY'))
这篇关于使用moment.js排序:弃用警告:提供的值不是可识别的RFC2822或ISO格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!