How do I change date formatting in Javascript to enable sorting?

后端 未结 2 725
無奈伤痛
無奈伤痛 2021-01-28 01:37

I am writing my dates of birth in the following manner:

  • 4.02.1976 14:37
  • 1.7.1990 11:35
  • 10.10.1910 18:00

I wanted to sort it using

相关标签:
2条回答
  • 2021-01-28 01:54

    A working version with optional time values.

    var obj = [{
        "id": 1,
        "dateOfBirth": "1.7.1990"
      },
      {
        "id": 4,
        "dateOfBirth": "4.02.1976 14:37"
      }, {
        "id": 2,
        "dateOfBirth": "28.10.1950 2:15"
      }
    ];
    
    console.log(
      obj.sort(function(a, b) {
        return parseDate(a.dateOfBirth) -
          parseDate(b.dateOfBirth);
      })
    );
    
    function parseDate(str) {
      var tokens = str.split(/\D/);
      while (tokens.length < 5)
        tokens.push(0);
    
      return new Date(tokens[2], tokens[1]-1, tokens[0], tokens[3]||0, tokens[4]||0);
    }

    0 讨论(0)
  • 2021-01-28 02:13

    Since you just have the year/month/day, it's pretty trivial to split up the dateOfBirth string, convert to a single number, and sort by that number, without any need to mess with Dates:

    var obj = [{
      "id": 1,
      "dateOfBirth": "1.7.1990"
    }, {
      id: 2,
      dateOfBirth: "28.10.1950"
    }, {
      "id": 4,
      "dateOfBirth": "4.02.1976"
    }];
    
    function valueFromDOBString(str) {
      const values = str.split('.').map(Number);
      return values[0] + values[1] * 100 + values[2] * 10000;
    }
    const sortedObj = obj.sort((a, b) => {
      return valueFromDOBString(b.dateOfBirth) - valueFromDOBString(a.dateOfBirth);
    });
    console.log(sortedObj);

    0 讨论(0)
提交回复
热议问题