Sorting UK Date format in JQuery Datatables

Dec 1, 2011

DataTablesDataTables are a brilliant plugin for JQuery that restyle and add functionality to your tables. They add searching, pagination and sorting right out of the box with very little configuration needed – unfortunately the sorting doesn’t support the UK date format so you need to add your own sorting methods – basic ones are supplied by the site itself but I have added a couple of tweaks to handle blank dates.

I simply create a separate javascript file that I load after the main datatables javascript. The datatables require you define three functions for a new method of sorting.

  • Type detection – jQuery.fn.dataTableExt.aTypes.unshift
  • Sort Ascending – jQuery.fn.dataTableExt.oSort[‘type-asc’]
  • Sort Descending – jQuery.fn.dataTableExt.oSort[‘type-desc’]

I place all of these in the new javascript file. Instructions and example functions can be found on the datatables site, one page for the type detection and one for the [sorting functions][2]. The below functions are based on the code found here.

The Type detection function simply defines a way of checking for the type of sort you want, in this example that is done using a regular expression and when UK style dates are found it names then as “uk_date”.

The sorting functions use this name “uk_date” and provide simple functions for comparing one date against another. My addition here is to check for dates that contain both / and – delimiters and for blank dates. The functions simply return -1, 0 or 1 like most compare functions. The code for this is below, hope it helps somebody out.

// type detection - UK date
jQuery.fn.dataTableExt.aTypes.unshift(
    function ( sData )
    {
        if (sData !== null && sData.match(/^(0[1-9]|[12][0-9]|3[01])[\\/-](0[1-9]|1[012])[\\/-](19|20|21)\\d\\d$/))
        {
            return 'uk_date';
        }

        return null;
    }
);

// sorting - UK date
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;

    if (isNaN(x)) { x = 0; }
    if (isNaN(y)) { y = 0; }

    console.log("sort: " + x + "," + y + ": " + ((x < y) ? -1 : ((x > y) ?  1 : 0)));

    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;

    if (isNaN(x)) { x = 0; }
    if (isNaN(y)) { y = 0; }

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

[2]: http://datatables.net/plug-ins/sorting