slund slund - 5 months ago 17
Node.js Question

Javascript sorting dates in the wrong order

I can't figure out why Javascript (running in Chrome, Safari, or NodeJS) seemingly sorts these dates incorrectly:

> [
"2014-05-01T08:06:00.000Z",
"2014-05-01T06:26:00.000Z",
"2014-05-01T06:27:00.000Z"
].map(function(x) {return new Date(x)}).sort()


produces

[ Thu May 01 2014 01:06:00 GMT-0700 (PDT),
Wed Apr 30 2014 23:26:00 GMT-0700 (PDT),
Wed Apr 30 2014 23:27:00 GMT-0700 (PDT) ]


I have looked for odd time changes around that date but can't find any.

Answer

Simply calling sort method will basically sorting based on string comparison. So for sorting based on date object use custom sort function.

console.log(
  [
    "2014-05-01T08:06:00.000Z",
    "2014-05-01T06:26:00.000Z",
    "2014-05-01T06:27:00.000Z"
  ].map(function(x) {
    return new Date(x)
  }).sort(function(a, b) {
    return a - b;
  })
)


If you want to sort the original array then avoid map method and inside the compare function parse the date string before taking difference.

console.log(
  [
    "2014-05-01T08:06:00.000Z",
    "2014-05-01T06:26:00.000Z",
    "2014-05-01T06:27:00.000Z"
  ].sort(function(a, b) {
    return new Date(a) - new Date(b);
  })
)

Comments