1

I'm using jQuery DataTable and the first column contain a custom date range. For ex: 22 Oct 2015 - 22 Nov 2015 where 22 Oct 2015 is the start date and 22 Nov 2015 is the end date. I want the sorting functionality to work on start date.

Let me explain a scenario: Let say I have 4 rows in DataTable and the first column date values are:

  • 25 Aug 2016 - 21 Sep 2016
  • 22 Oct 2015 - 22 Nov 2015
  • 21 Oct 2015 - 21 Nov 2015
  • 02 Dec 2015 - 02 Jan 2016

I want the sorting result in following format:

  • 25 Aug 2016 - 21 Sep 2016
  • 02 Dec 2015 - 02 Jan 2016
  • 22 Oct 2015 - 22 Nov 2015
  • 21 Oct 2015 - 21 Nov 2015

How to do this!

1 Answer 1

2

You must implement your own sorting plugin to do that. It is quite simple :

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
    "date-range-pre": function ( a ) {
        a = a.split('-')[0].trim();
        return Date.parse(a);   
    },
     "date-range-asc": function ( a, b ) {
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    },
     "date-range-desc": function ( a, b ) {
        return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    }
} );

The above simply extracts the first date by splitting the string and then do the sorting on that. There is no error handling, i.e care taking of empty strings and so on - you can do that yourself. Usage :

var table = $('#example').DataTable({
    columnDefs: [
       { type: 'date-range', targets: 0 }
    ]
}) 

demo -> http://jsfiddle.net/gs5syg70/

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

1 Comment

Asc sorting is simple as return b - a and desc sorting would be return a - b; (or may be it is the other way round but you get the point).

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.