DataTables is an awesome “do-it-all” table plugin for jQuery. I was trying to display a locally formatted date but should still be sorted correctly. Current plugins may not work since it the date format uses long date format like “20 June 2015”. Therefore, I have to roll out my own plugin to use a hidden timestamp instead.
Table Definition
Below is the snippet from my table definition showing a single row with data being populated via PHP script.
1 2 3 4 5 6 7 8 9 10 11 | <tr> <td>Title</td> <td> <?php $d = new DateTime( $row ->date_created); ?> <span data-timestamp= "<?php echo $d->format('U') ?>" ><?php echo $d ->format( 'j F Y' ) ?></span> </td> <td> <a href= "#" class = "btn-edit" >Edit</a> | <a href= "#" class = "btn-delete" > Delete </a> </td> </tr> |
We need to be able to sort the first and second column. The first column is easy since it is just a simple title string. The second column is where we would like to customize since we are showing a formatted date but we will sort it via timestamp data attribute.
Plugin
We should define our plugin after the DataTables plugin script included but before we initialize our tables.
1 2 3 4 5 | $.fn.dataTable.ext.order[ 'dom-data-timestamp' ] = function (settings, col) { return this .api().column( col, {order: 'index' } ).nodes().map( function (td, i) { return parseInt($(td).find( 'span' ).attr( 'data-timestamp' )); }); }; |
Our plugin simply reads the data-timestamp
attribute from a span
inside the table cell, then we treat it as integer when we define it’s column sorting definition.
Initialization
Below is out initialization code. We define the second column’s sorting information, specify the plugin name dom-data-timestamp
and finally treat it as integer. We also make the second column sorted descending by default, but still allow column one to be sorted by the user.
1 2 3 4 5 6 7 8 9 10 | $( '#my-table' ).dataTable({ 'paging' : false , 'bInfo' : false , 'columns' : [ null , { 'orderDataType' : 'dom-data-timestamp' , 'type' : 'numeric' }, { 'orderable' : false } ], 'order' : [[ 1, 'desc' ]] }); |
By the way, we disable the third column’s sorting capability from the user although we can still sort it via API.
Enjoy and share.
Thanks for these tips.
In my case, with a timestamp ISO 8601 (YYYY-MM-DDThh:mm:ssTZD like 2017-07-16T19:20:30+01:00) and DataTables v1.10.15 it didn’t work with parseInt (). By removing it :
$.fn.dataTable.ext.order[‘dom-data-timestamp’] = function(settings, col) {
return this.api().column( col, {order:’index’} ).nodes().map(function (td, i)
return $(td).find(‘span’).attr(‘data-timestamp’);
});
};
It works as expected.
Yeah, I used the unix timestamp format for this example which is numeric and is easier to sort.