0

I'm using the datatable jQuery plugin; it works fine when sorting columns that contain text and numbers, but I have an issue with sorting columns that contain date values.

For example when I click on the date column I get:

01-03-2012
27-02-2012
29-02-2012
...
...

However the real order should be like this:

01-03-2012
29-02-2012
27-02-2012

NB: I'm using the French date format d-m-Y.

1 Answer 1

1

Did you look at the Sorting plug-ins page?

The following is copied directly from that page. You might have to tweak the code a bit (for example, splitting on - rather than /, etc.) but most of the work is done for you:

Date (dd/mm/YY)

DataTables internal date sorting replies on Date.parse() which is part of the Javascript language, but you may wish to sort on dates which is doesn't recognise. The following is a plug-in for sorting dates in the format dd/mm/yy. Note a type detection plug-in is provided to automatically select this type of sorting when needed.

jQuery.fn.dataTableExt.oSort['uk_date-asc']  = function(a,b) {
    var ukDatea = a.split('/');
    var ukDateb = b.split('/');

    var x = (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
    var y = (ukDateb[2] + ukDateb[1] + ukDateb[0]) * 1;

    return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['uk_date-desc'] = function(a,b) {
    var ukDatea = a.split('/');
    var ukDateb = b.split('/');

    var x = (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
    var y = (ukDateb[2] + ukDateb[1] + ukDateb[0]) * 1;

    return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
};
Sign up to request clarification or add additional context in comments.

1 Comment

How to add this code to the plugin or how to call this function to sort only when clicked on date column...?

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.