M. Gar
M. Gar

Reputation: 887

Datatable sort by date correctly

I'm using Django framework for my web site but to show info I use the plugin Datatable so one column show date info, the format that is used to show the date is like May. 6, 2017 so when I sort the date column take the order as string and not date so the first date to show is like August 10, 2017 Is there a way to sort by date using that format?

Upvotes: 1

Views: 1052

Answers (1)

Bertrand Martin
Bertrand Martin

Reputation: 552

When defining the columns of your DataTable, you need to specify the render callback as in the example below:

        columns: [
            {
                title: "Date",
                data: "yourDateRef",
                render: function(data, type, row) {
                    if (type == "display") {
                        return prettyFormat(data);
                    }
                    else {
                        return data;
                    }
                }
            },
            ...

Basically, DataTables calls the render callback to display the data (type=="display"), but also when the data needs to be sorted (type=="sort"), or filtered (type=="filter").

This allows you to control how a given field is displayed, but also sorted and filtered.

More information: https://datatables.net/reference/option/columns.render

Hope this helps!

Upvotes: 1

Related Questions