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, 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With