Datatable date sorting dd/mm/yyyy issue

2019-01-08 07:49发布

I am using a Jquery plugin called datatables

Its fantastic, however I cannot get the dates to sort correctly according to the dd/mm/yyyy format.

I have looked at their support formats but none of these fixes seem to work.

Can anybody here help me please?

23条回答
神经病院院长
2楼-- · 2019-01-08 08:23

Try this plugin.

As stated here you need to include Moment.js and the datatable-moment plugin, then just declare the date format you are using. The plugin will autodetect your date columns and sort it like it should be. For moment.js format explanations, check here.

Example:

$(document).ready(function() {
    $.fn.dataTable.moment('DD/MM/YYYY HH:mm');
    $('#example').DataTable();
});
查看更多
Viruses.
3楼-- · 2019-01-08 08:24

use this snippet!

$(document).ready(function() {
 $.fn.dataTable.moment = function ( format, locale ) {
    var types = $.fn.dataTable.ext.type;

    // Add type detection
    types.detect.unshift( function ( d ) {
        return moment( d, format, locale, true ).isValid() ?
            'moment-'+format :
            null;
    } );

    // Add sorting method - use an integer for the sorting
    types.order[ 'moment-'+format+'-pre' ] = function ( d ) {
        return moment( d, format, locale, true ).unix();
    };
};

$.fn.dataTable.moment('DD/MM/YYYY');

$('#example').DataTable();
});

the moment js works well for all date and time formats, add this snipper before you initialize the datatable like i've done earlier.

Also remember to load the http://momentjs.com/

查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-08 08:24

What seems to work for me was

push the full datetime object fetched with a select query from my db in a dataset wich will be draw by datatable format "2018-01-05 08:45:56"

then

    $('#Table').DataTable({
        data: dataset,
        deferRender: 200,
        destroy: true,
        scrollY: false,
        scrollCollapse: true,
        scroller: true,
        "order": [[2, "desc"]],
        'columnDefs': [
            {
                'targets': 2,
                'createdCell':  function (td, cellData, rowData, row, col) {                        
                    var datestamp = new Date(cellData);
                    $(td).html(datestamp.getUTCDate() + '-' + (datestamp.getMonth()+1) + '-' + datestamp.getFullYear());
                }
            }
        ],
        "initComplete": function(settings, json) {
            $($.fn.dataTable.tables(true)).DataTable()
                .columns.adjust();               
        }
    });

Rows get sorted right , then I get a html I want in the row

查看更多
Summer. ? 凉城
5楼-- · 2019-01-08 08:24

To the column you want ordering keep "sType": "date-uk" for example:-"data": "OrderDate", "sType": "date-uk" After the completion of Datatable script in ajax keep the below code

 jQuery.extend(jQuery.fn.dataTableExt.oSort, {
            "date-uk-pre": function (a) {
                var ukDatea = a.split('/');
                return (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
            },

            "date-uk-asc": function (a, b) {
                return ((a < b) ? -1 : ((a > b) ? 1 : 0));
            },

            "date-uk-desc": function (a, b) {
                return ((a < b) ? 1 : ((a > b) ? -1 : 0));
            }
        });

Then You will get date as 22-10-2018 in this format

查看更多
贼婆χ
6楼-- · 2019-01-08 08:25

An other solution : https://datatables.net/blog/2014-12-18

with 2 javascripts libs : //cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js and //cdn.datatables.net/plug-ins/1.10.15/sorting/datetime-moment.js

then only this :

$(document).ready(function() {

$.fn.dataTable.moment( 'DD/MM/YYYY' );

$('#example').DataTable(); 

} );

查看更多
Lonely孤独者°
7楼-- · 2019-01-08 08:29

If you get your dates from a database and do a for loop for each row and append it to a string to use in javascript to automagically populate datatables, it will need to look like this. Note that when using the hidden span trick, you need to account for the single digit numbers of the date like if its the 6th hour, you need to add a zero before it otherwise the span trick doesn't work in the sorting.. Example of code:

 DateTime getDate2 = Convert.ToDateTime(row["date"]);
 var hour = getDate2.Hour.ToString();
 if (hour.Length == 1)
 {
 hour = "0" + hour;
 }
 var minutes = getDate2.Minute.ToString();
 if (minutes.Length == 1)
 {
 minutes = "0" + minutes;
 }
 var year = getDate2.Year.ToString();
 var month = getDate2.Month.ToString();
 if (month.Length == 1)
 {
 month = "0" + month;
 }
 var day = getDate2.Day.ToString();
 if (day.Length == 1)
 {
 day = "0" + day;
 }
 var dateForSorting = year + month + day + hour + minutes; 
 dataFromDatabase.Append("<span style=\u0022display:none;\u0022>" + dateForSorting +
 </span>");
查看更多
登录 后发表回答