如何在Jquery中排序日期数组?

时间:2014-05-20 06:00:24

标签: jquery sorting date

我有一系列日期如下:

var unavailableDates = ["31-5-2014", "1-6-2014", "2-6-2014", "3-6-2014", "26-5-2014", "27-5-2014", "28-5-2014", "29-5-2014"];

如何在不更改日期格式的情况下对此数组进行排序?

4 个答案:

答案 0 :(得分:2)

代码说明一切。

var unavailableDates = ["31-5-2014", "1-6-2014", "2-6-2014", "3-6-2014", "26-5-2014", "27-5-2014", "28-5-2014", "29-5-2014"];
unavailableDates = unavailableDates
    .map(function (val, idx) {
        var arr = val.split('-');
        return new Date(arr[2], arr[1] - 1, arr[0]);
    })
    .sort(function (x, y) {
        return x > y
    });
console.log(unavailableDates);

DEMO

答案 1 :(得分:2)

希望它对你有用,试试这段代码

  var unavailableDates = ["31-5-2014", "1-6-2014", "2-6-2014", 
              "3-6-2014", "26-5-2014", "27-5-2014", "28-5-2014", "29-5-2014"];
    function SortByDate(a, b){
       var amyDate = a.split("-");
       var aNewDate=new Date(amyDate[1]+","+amyDate[0]+","+amyDate[2]).getTime();
       var bmyDate = b.split("-");
       var bNewDate=new Date(bmyDate[1]+","+bmyDate[0]+","+bmyDate[2]).getTime();
       return ((aNewDate < bNewDate) ? -1 : ((aNewDate > bNewDate) ? 1 : 0));
    }
    console.log(unavailableDates.sort(SortByDate));

FIDDLE DEMO

答案 2 :(得分:0)

此备选方案应该可以正常工作,并且根本不会更改日期格式。 sort函数使用日期格式YYYYMMDD仅用于排序,但保留原始日期。

var unavailableDates = ["31-5-2014", "1-6-2014", "2-6-2014", "3-6-2014", "26-5-2014", "27-5-2014", "28-5-2014", "29-5-2014"];
unavailableDates.sort(function( a, b ) {
    var sA = a.split( '-' ).map(function(v,i) { return (i<2)?("0"+v).substr(-2):v; }).reverse().join(''); 
    var sB = b.split( '-' ).map(function(v,i) { return (i<2)?("0"+v).substr(-2):v; }).reverse().join('');
    return sA > sB;
})
console.log( unavailableDates );

JS DEMO

答案 3 :(得分:0)

var eventDates = ["31-5-2014", "1-6-2014", "2-6-2014", "3-6-2014", "26-5-2014", "27-5-2014", "28-5-2014", "29-5-2014"];
           
var result = data.sort(function (a, b){ new Date(a.eventDates).getTime() - new Date(b.eventDates).getTime()
});

console.log(result);