How Sort Array Date JavaScript dd/mm/yyyy?

前端 未结 5 1851
梦毁少年i
梦毁少年i 2020-12-10 08:17

How would I sort an array of dates in chronological order? For example I have:

var dates = [
    \'03/03/2014\',
             


        
相关标签:
5条回答
  • 2020-12-10 08:35

    Please do this the easy way.
    Works for dates formatted as 'dd/mm/yy' or 'dd/mm/yyyy'.

    var dates = [
        '03/03/2014',
        '01/03/2014',
        '02/03/2014',
        '04/03/2014'
    ];
    
    dates.sort( function(c,d){
        var rx = /(\d+)\/(\d+)\/(\d+)/;
        var a = Number(c.replace(rx, '$3$1$20000'));
        var b = Number(d.replace(rx, '$3$1$20000'));
        return a > b ? -1 : a == b ? 0 : 1; // for newer on top
        //return a < b ? -1 : a == b ? 0 : 1; // for older on top
      });
    
    0 讨论(0)
  • 2020-12-10 08:39

    Digigizmo answer works!

    in case: dd/mm/yyyy hh:mm:ss you can use:

    list.sort(function (a, b) {
        var aa = a.substring(0, 10).split('/').reverse().join() + replaceAll(':', '', a.substring(11, 20)),
        bb = b.substring(0, 10).split('/').reverse().join() + replaceAll(':', '', b.substring(11, 20));
        return aa < bb ? -1 : (aa > bb ? 1 : 0);
    });
    

    and replaceAll function:

    function replaceAll(find, replace, str) {
      return str.replace(new RegExp(find, 'g'), replace);
    }
    
    0 讨论(0)
  • 2020-12-10 08:40

    Try this (feel free to ask for details) :

    dates.sort(function (a, b) {
        // '01/03/2014'.split('/')
        // gives ["01", "03", "2014"]
        a = a.split('/');
        b = b.split('/');
        return a[2] - b[2] || a[1] - b[1] || a[0] - b[0];
    });
    

    Translation of the last line :

    return          return
    a[2] - b[2]     years comparison if year A - year B is not 0
    ||              or
    a[1] - b[1]     months comparison if month A - month B is not 0
    ||              or
    a[0] - b[0];    days comparison
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort.

    0 讨论(0)
  • 2020-12-10 08:41

    Assuming your date format is consistently DD/MM/YYYY:

    dates.sort(function(a, b){
        var aa = a.split('/').reverse().join(),
            bb = b.split('/').reverse().join();
        return aa < bb ? -1 : (aa > bb ? 1 : 0);
    });
    

    ... otherwise you will have to compare Date objects if you require more flexibility.

    0 讨论(0)
  • 2020-12-10 08:44

    Just improving @leaf answer as split works on strings so you might get error if the type of 'a' and 'b' is object.

    dates.sort(function (a, b) {
            a = a.toString().split('/');
            b = b.toString().split('/');
            return a[2] - b[2] || a[1] - b[1] || a[0] - b[0];
        });
    
    0 讨论(0)
提交回复
热议问题