0

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

1 Answer 1

1
$.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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, believe that would work, but it is also based on a typical misunderstanding on custom sorting plugins : The usage of both a -pre and -asc and -desc functions does not make much sense. Either you have a -pre function that delivers fixed values to dataTables autodetected type based sorting, or you have -asc and -desc methods that do all the work. You cannot have both. Try the code out, I am sure the date-time-odd-asc and date-time-odd-desc is never executed at all. I have had this misunderstanding myself as well, also many old plugins contain this redundancy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.