Jerlam
Jerlam

Reputation: 1101

Sorting date (Y-M-D h-m-s) not sorting correctly

I have a list of objects that I want to sort by date of creation. Here is my relevant code:

  dateToLocalString(date) {
    date = new Date(date);
    const year = date.getFullYear();
    const month = date.getMonth() < 10 ? "0" + date.getMonth() : date.getMonth();
    const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    const hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    const minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    const seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : 
    date.getSeconds();

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

 const AscOrder = function x(order) {
      return function(a, b) {
        if(order === 'status') {
          if(a[order].split(' ')[1] < b[order].split(' ')[1]) return -1;
          if(a[order].split(' ')[1] > b[order].split(' ')[1]) return 1;
          return 0;
        }
        if(a[order] < b[order]) return -1;
        if(a[order] > b[order]) return 1;
        return 0;
      };
    };


switch (this.state.sortDevSpacesBy) {
  case 'CREATED' : devSpaceList.sort(AscOrder('createdAt'));
    break;
  case 'CREATED_DESC' : devSpaceList.sort(DescOrder('createdAt'));
    break;
}

But it doesn not sort my dates correctly, Y-M-D is sorted correctly, but then there seems to be a problem with the time:

Descending order: - 2018-04-24 12:53:50 - 2018-05-15 15:21:15 - 2018-05-15 15:03:04 - 2018-05-15 11:55:07

Upvotes: 1

Views: 331

Answers (1)

kmiklas
kmiklas

Reputation: 13463

For reasons like this, I usually convert all dates to time since epoch before sorting; e.g.:

let d = new Date()
d.getTime() //-> 1529070578437

This effectively removes lots of tricky edge cases (such as leap years) and other complex conversion routines.

I work with the dates as much as possible in this format, and convert only when necessary; e.g., displaying to User in their locale format.

Upvotes: 2

Related Questions