简体   繁体   English

排序日期(YMD hms)排序不正确

[英]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, YMD is sorted correctly, but then there seems to be a problem with the time: 但是它不能正确排序我的日期,YMD也没有正确排序,但是时间似乎有问题:

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 降序:-2018-04-24 12:53:50-2018-05-15 15:21:15-2018-05-15 15:03:04-2018-05-15 11:55:07

For reasons like this, I usually convert all dates to time since epoch before sorting; 由于这样的原因,我通常将所有日期转换为自纪元以来的时间; eg: 例如:

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

This effectively removes lots of tricky edge cases (such as leap years) and other complex conversion routines. 这有效地消除了许多棘手的情况(例如leap年)和其他复杂的转换例程。

I work with the dates as much as possible in this format, and convert only when necessary; 我会尽可能以这种格式处理日期,并仅在必要时进行转换; eg, displaying to User in their locale format. 例如,以其区域设置格式向用户显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM