javascriptjqueryangularjsdatatablesangular-datatables

Angular-Datatables wrong sorting on date


I'm using the angular-datatables plugin in my project, which works fine on all types, except for dates.

Example DESC:

Example ASC:

I'm using the Angular Way with a date filter in my ng-repeat. I have a suspicion that it sorts with a wrong date format. I would like it to sort based on the day. How can I fix this?

<table class="table table-hover" datatable="ng">
        <thead>
            <tr>
                <th>Client</th>
                <th>Project</th>
                <th>ID</th>
                <th>Inv. Date</th>
                <th>Start Date</th>
                <th>End Date</th>
                <th>DKK ex VAT</th>
                <th>CIG</th>
                <th>Attention</th>
                <th>Cust. Manager</th>
                <th>Regarding</th>
                <th>Due Date</th>
                <th>Finalized</th>
                <th>Paid</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="invoice in vm.latestInvoices.LatestInvoices">
                <td>{{invoice.CompanyName}}</td>
                <td>{{invoice.ProjectName}}</td>
                <td>{{invoice.InvoiceID}}</td>
                <td>{{invoice.InvoiceDate | date: 'dd/MM/yyyy'}}</td>
                <td>{{invoice.InvoiceStart | date: 'dd/MM/yyyy'}}</td>
                <td>{{invoice.InvoiceEnd | date: 'dd/MM/yyyy'}}</td>
                <td>{{invoice.DKKexVAT}}</td>
                <td>{{invoice.CustomerInvoiceGroup}}</td>
                <td>{{invoice.Attention}}</td>
                <td>Customer Manager</td>
                <td>{{invoice.Regarding}}</td>
                <td>{{invoice.DueDate | date: 'dd/MM/yyyy'}}</td>
                <td>No</td>
                <td>{{invoice.Paid}}</td>
            </tr>
        </tbody>
    </table>

Solution

  • dataTables generally does a good job by detecting datatypes for each column. However, if the type detection meets anything that conflicts with for example assumed numbers, the column is turned into default alpha sorting. I strongly believe this is the case here - if the rendered content meets the dd/MM/yyyy criteria 100%, then dataTables should automatically sort that column as date.

    Luckily we can force the date datatype through the columns / columnDefs settings. Use for example DTColumnDefBuilder :

    $scope.dtColumnDefs = [  
        DTColumnDefBuilder.newColumnDef([3,4,5,11]).withOption('type', 'date')
    ];
    

    This forces column 3,4,5 and 11 to be of type date. Include dtColumnDefs in the markup :

    <table class="table table-hover" datatable="ng" dt-column-defs="dtColumnDefs">
    

    Example - try to comment out the .withOption('type', 'date') and see the difference -> http://plnkr.co/edit/XpBcLhlm0Frq3voN6X97?p=preview