Reputation: 4278
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?
Upvotes: 5
Views: 10089
Reputation: 350750
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, call format
at that very time.
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>
Upvotes: 8
Reputation: 112
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'))
Upvotes: 3