How to Sort Different Date Formats with jQuery DataTables

DataTables is a robust library to add many features to a simple table. Sorting is one of those powerful features. DataTables has a built-in date sorting which relies on Date.parse(), a part of the Javascript language. However, there are some formats which can’t be recognized by this library. Many users get stuck when it comes to sorting date with certain formats such as dd-mm-yyyy and dd/mm/yyyy. 

Create a custom sort function for DataTables

Let’s create a DataTables plugin which can sort dd-mm-yyyy format. Firstly, we need to extend oSort function to define a custom sort type.

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
	"date-custom-pre": function ( a ) {
	    var customDate = a.split('-');
	    return (customDate[2] + customDate[1] + customDate[0]) * 1;
	},

	"date-custom-asc": function ( a, b ) {
	    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
	},

	"date-custom-desc": function ( a, b ) {
	    return ((a < b) ? 1 : ((a > b) ? -1 : 0));
	}
});

Other formats can be implemented in the same way. You just need to replace the split character.

Implement sorting

We will use “aoColumns”: [] to apply custom sort types to certain columns. The script below applies new custom date format sorting to 3th and 4th columns of a table with 8 columns.

$('.mytable').DataTable({
        "paging": true,
        "pageLength": 10,
        "info": false,
        "searching": false,
        "scrollX": true,
        "bAutoWidth": false,
        "order": [], 
        "columnDefs": [ {
            "targets": [1,7,8],
            "orderable": false
            }],
        "aoColumns": [
            null,
            null,
            { "sType": "date-custom" },
            { "sType": "date-custom" },
            null,
            null,
            null,
            null,            
            null
        ]
    });

Null is used on columns which don’t require implementation of any custom sort functions.

Leave a Comment

Your email address will not be published. Required fields are marked *

We care about your privacy and data security. Google serves cookies to analyse traffic and show ads on this site. By using this site you agree to these cookies being set. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close