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;
my
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>
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'))