Simple way to sort dates in any format with jquery.datatables

Initially, I was formatting the date in my table using any format I liked. However, I soon realized that this would ruin sorting. For example, if you have a table with dates formatted as “dd/mm/yyyy” and “mm/dd/yyyy”, datatables will sort them incorrectly because it will sort them based on their underlying serial numbers.

Then I got to thinking, datatables just sorts numerically, so putting something hidden at the start of the text in the table will get sorting working again. Here’s an example of how you can do this – (note – this is asp mvc razor syntax, but the method can be adapted to any language):

<td> @if (item.CreateDate != null) {<text>@item.CreateDate.Value.Ticks </text>}</td>

The only caveat is that perhaps when exporting the table, the hidden text may show… I haven’t tried this yet! 😅👍


Posted

in

,

by

Comments

Leave a Reply

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