MaylorTaylor
MaylorTaylor

Reputation: 5041

DataTables JS does not sort date correctly in PHP application

I was tasked to fix this table sorting in this PHP app. The table uses DataTable 1.10 to auto generate the datatable for the php blade.php file.

The data coming into the page uses the following format for the "Publish Date":

uploaded_at: "2018-01-02 00:00:00"

page.blade.php

<table class="table tbl_issue" cellspacing="0" style="border: 1px solid #e9ecef;border-radius: 4px;">
                        <thead>
                            <tr>
                                <th>Issue Title</th>
                                <th>Publish Date</th>
                            </tr>
                        </thead>
                        <tbody>
                            @if(count($data['issues']))
                                @foreach($data['issues'] as $issue)
                                @if($issue->uploaded_at >= $data['starts_date'])
                                <tr>
                                    <td>
                                        {{$issue->name}}
                                    </td>
                                    <td>{{date('m/d/Y', strtotime($issue->uploaded_at))}}</td>
                                </tr>
                                @endif
                                @endforeach
                        </tbody>
                    </table>

$(document).ready(function(){
    $('.tbl_issue').DataTable();
});

When I click the auto-generated "publish date" filter, the dates are not sorted correctly. (images below)

ASC DSC

As you can see, the 08/18/2016 date is always in the middle.

How can i get this sorting dates correctly?

Upvotes: 0

Views: 586

Answers (1)

thecoolestguyever123
thecoolestguyever123

Reputation: 983

Try using the Datatables API to set that column as type date.

Example:

$('#example').dataTable( {
  "columns": [
      { "type": "string" },
      { "type": "date" },
  ]
} );

See reference:

https://datatables.net/reference/option/columns.type

Upvotes: 1

Related Questions