Enriqe
Enriqe

Reputation: 567

Sorting dates in DataTables? (function override)

DataTables properly sort dates in YYYY-MM-DD format only. All other formats they sort as string.

As far as I'm not a fan of adding a library / plugin for every functionality into my projects I tried to solve it by myself.

DataTables are using Date.parse() function to "understand" the date and sort it. (according to https://datatables.net/blog/2014-12-18). So I decided to override that function and modify it in the way it will "understand" also other date formats.

I added this JS into my code:

            let origFunction = Date.parse;

            Date.parse = function(str) {

                // I want to parse this date format: 27.01.2018
                if (str.indexOf('.') > 0) {
                    str = convertDateToISO(str); // my function translates date into 2018-01-27
                }
                return origFunction(str);
            };

When I test this in the browser console, Date.parse works perfectly fine with my date format, but DataTables keep sorting my european dates as strings.

Any idea what I'm doing wrong? Or is it possible to do it this way?

SOLVED:

After all it looks like really the easiest way is to include "Moment.js" plugin as described here: https://datatables.net/blog/2014-12-18#Operation But while there was a "no plugin" requirement in my question, I'm accepting answer of @billynoah as a solution too.

Upvotes: 3

Views: 307

Answers (1)

You Old Fool
You Old Fool

Reputation: 22959

You probably want to take a look at orthogonal-data. This allows you to define a custom value for sorting your column. In this case, the most straightforward thing to do is use a timestamp for sorting and then you can display date in any format you want. For data sourced from an object or ajax you can structure your column definition like:

{
    data: 'date',
    render: {
        _: 'display',
        sort: 'timestamp'
    }
}

For html source you can use the data-order attribute:

<td data-order="1545466488">Sat, Dec 22nd 2018</td>

(Disclaimer / Attribution: This is all more or less straight out of the manual linked above)

Upvotes: 2

Related Questions