I’m a big fan of jQuery DataTables plugin and have been using them for a little while now. I am a Moodle developer by profession and quite a few Moodle plugins use jQuery DataTables as their weapon of choice. DataTables can be easily added to any project using the documentation available on their website¬†https://datatables.net/. I was working on a plugin today that needed the data to be displayed in the attached format. Note the date format and the default sorting that was needed to display the data.

jQuery DataTables and Date Column sorting

 

To achieve the above mentioned table format and sorting, I used PHP to generate the data and created a standard html table. Then to achieve default sorting and allow further sorting on the date column by the user, I used the DataTables’ datetime-moment plugin and MomentJS library along with jQuery DataTables plugin.

 

PHP Code to generate the date:

 

HTML code to generate the table

 

Javascript to create the datatables:

 

And now the actual reason behind writing this post:

I was able to build the above mentioned pretty quickly and everything was working as expected on my development machine. After testing with a few data combinations, I uploaded the code to the server. And now to my surprise, date sort was not working as expected and the column was not being sorted by the date. I spent hours trying to figure out what actually was going on as the same code was working on the development machine but was not working on the server with similar environments. Turns out that for some reason, the column was being treated as text instead of date and hence the unexpected behaviour. If you come across something similar, you add the following options to your DataTables call:

 

And bam…. it worked on the production site too…

Hope this helps someone who is stuck at this or will get stuck in future.