Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

How can I sort my jquery datatable by date?

This is the content of my datatable:

05.06.2020 10:46
14.08.2020 11:18
17.09.2020 01:24
17.09.2020 04:42
20.08.2020 01:47
20.08.2020 04:37
22.09.2020 02:05
23.09.2020 13:52
28.04.2020 02:46
28.04.2020 12:00

The sorting is not working correctly, as I am expecting the colums start with the newest date. This is my approach:

var table = $('.table').DataTable({
    "data":{{ data|raw }},
    "order": [[ 0, "asc" ]],
  ....

   'createdCell':  function init(cell, cellData, rowData, rowIndex, colIndex) {
       var unixTimestamp = moment(cellData, 'DD.MM.YYYY HH:MM').unix();
        $(cell).html(cellData);
        $(cell).attr('data-order', unixTimestamp);
   }

But still the sorting is wrong. I tried this solution How can I sort my DataTables row by date? but it did not work for me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can add the timestamp into your object and use Orthogonal data. I could give you an example more specific to your case if you provide a snippet of the the object and more of your Datatables init params, but it's something like this:

var table_data = [
    {
        "date": {
            "display": "05.06.2020 10:46",
            "timestamp": "1303681234"
        }
    }
]

var table = $('.table').DataTable({
    "data": table_data,
    "order": [[ 0, "asc" ]],
    "columns" : [{
        data: {"_" : "date.display", "sort" : "date.timestamp" },
    }]
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...