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?
As stated by others the format "DD/MM/YYYY" is not an ISO 8601 format and the resulting strings can be ambiguous.
You should really work with Date or moment objects, not strings.
So don't call
format
when you store the dates in your array objects. If ever you need to render the date, callformat
at that very time.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 thediff
. So you could doreturn moment.utc(left.timeStamp, 'DD/MM/YYYY').diff(moment.utc(right.timeStamp, 'DD/MM/YYYY'))