An RoR solution to DataTables date column sorting

An RoR solution to DataTables date column sorting

It's a little bit daunting if you look for solutions presented at the official DataTables site offering different solutions for sorting different kinds of data columns, especially for dates.

While the availability of different plugins are quite confusing to use, there's an HTML5 compliant way of adding "intelligence" on how to sort your dates.

Dates can also be read/stored/displayed as a Time object.  And since Time can be rendered to a unique Integer representation, you can use this as a means of understanding how to sort your date columns.

  1. Study your data.

If you're working on a database that has quite old data stored in it, chances are, new data restrictions weren't in place before and you could end up with various unanticipated date formats.  In my case, some were even in words without recognisable patterns in some!

Here were some of the strings I encountered as, well, dates:

Oct '14
April 2014
Fall 2014
6/10/2014 or 6/11/2014

2.  Attempting to find a way to convert these to a Date Object

You may try to use any method or library or preferred way to convert these strings into Date objects.  In my case, we had the Chronic gem in our library, so that's what I'm going to use.

Oct '14 # inaccurate conversion
April 2014 # inaccurate conversion
3/12/14-3/12/15 # a single date should be picked
Fall 2014 # no conversion
6/10/2014 or 6/11/2014 # a single date should be picked

3.  Create a helper or library to handle different scenarios

4.  Add the helper to your actual table as such:

And it works! I hope this helps you fix your sorting without the need to reference external plugins or libraries.