简体   繁体   中英

JQuery DataTable Date Order

I have two problems.

In my table, there is a created date column and I am soring by this date. Unfortunately it sorts as string, instead of date. (I'm using nodejs).

it had to be

21.05.2019

22.04.2109

and my code :

"order": [[0,"desc"],[ 1, "desc" ],[ 7, "desc" ]],

I've tried a plugin as well

"columnDefs": [                                                
                    {
                        "targets": [ 1 ],
                        "visible": true,
                        "searchable": false
                    },
                    {
                        "targets":7,
                        "type": "date-de"
                    },


<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/
jquery.dataTables.js" type="text/javascript"></script>

<script src="https://cdn.datatables.net/plug-ins/1.10.19/sorting/date-de.js"
 type="text/javascript"></script>

$(document).ready(function() {
   jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "extract-date-pre": function(value) {
        var date = $(value, 'span')[0].innerHTML;
        date = date.split('/');
        return Date.parse(date[1] + '/' + date[0] + '/' + date[2])
    },
    "extract-date-asc": function(a, b) {
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    },
    "extract-date-desc": function(a, b) {
        return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    }
});

but did not work...

As I can see the date is in: DD.MM.YYYY format. To parse the date you need to split by . not / .

"extract-date-pre": function(value) {
    var date = $(value, 'span')[0].innerHTML;
    date = date.split('.').reverse().join('-');
    return Date.parse(date);
}

Please, only one question at once, remove the select part and create a new question with it.

Your first question: In order to the datatable to order the date in the right way, you must print the date as Year-Month-Day in a hidden element.

Example, I don't know how you populate your datetable, but in plain HTML you will do something like:

<tr>
 <td>
   <span style="display:none">2019-05-22</span>
    22-05-2019
 </td>
</tr>

So when the datatable orders the column, it picks the value inside the hidden span that now can be ordered as a simple string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM