Diamonte
Diamonte

Reputation: 413

Jquery datatables date sorting

I'm using jQuery DataTables, trying to sort data column with 2 different date types.

I have 2 different formats month/year and day/month/year but they are not sorting correctly.

Current code:

 function dateSorter(a, b) {
    var datea = a.split("/");
    var dateb = b.split("/");

    if (datea[1] > dateb[1]) return 1;
    if (datea[1] < dateb[1]) return -1;
  if (datea[0] > dateb[0]) return 1;
    if (datea[0] < dateb[0]) return -1;
    if( datea.length == 2 )
    {
    if (datea[2] > dateb[2]) return 1;
    if (datea[2] < dateb[2]) return -1;
    }
    else
    {
    if( datea[1] > dateb[2] ) return 1;
    if( datea[2] < dateb[1] ) return -1;
    }
    return 0;
}

Above is current code, it works for month/year format and sorts them fine , but not mixed with both formats.

This currently sorts day/month from day/month/year format but it does not sort year correctly.

Example (current):

03/04/2016
12/04/2017
12/05/2015
01/2015
02/2015
02/2016
01/2018
...

It should be:

01/2015
02/2015
12/05/2015
02/2016
03/04/2016
12/04/2017
01/2018

Upvotes: 0

Views: 645

Answers (1)

annoyingmouse
annoyingmouse

Reputation: 5699

$.extend( jQuery.fn.dataTableExt.oSort, {
    "date-time-odd-pre": function (a){
        if(/\d{1,2}\/\d{1,2}\/\d{4}/.test(a)){
            return parseInt(moment(a, "DD/MM/YYYY").format("X"), 10);
        }else{
            return parseInt(moment(a, "MM/YYYY").format("X"), 10);
        }
    },
    "date-time-odd-asc": function (a, b) {
        return a - b;
    },
    "date-time-odd-desc": function (a, b) {
        return b - a;
    }
});

Should work, though you'll need moment available.

Hope that helps.

Upvotes: 1

Related Questions