OammieR
OammieR

Reputation: 2860

How to sort date with yyyy-mm-dd format. By using datatables [js]?

I need to sort date with yyyy-mm-dd format.

From this document. Here is my code.

$( function () {
    $.fn.dataTable.moment('YYYY-MM-DD');

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

But I still got the wrong sort (See picture below)

enter image description here

How can I fix this?

Upvotes: 1

Views: 2787

Answers (1)

Shiffty
Shiffty

Reputation: 2156

If you check the unshift function in the datatable plugin you see that moment has the strict parameter defined true.

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

From the moment docs:

Moment's parser is very forgiving, and this can lead to undesired behavior. As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly.

So instead of:

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

which would require a date like 2015-04-01, you have to use:

$.fn.dataTable.moment('YYYY-M-D');

Upvotes: 6

Related Questions