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

后端 未结 2 726
無奈伤痛
無奈伤痛 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);
    }

提交回复
热议问题