3
votes

I am using DataTables and moment and have custom date format on my table. How can I sort the column by moment? Here you can see that sorting does not work correctly updated_at column. I am using Datatable moment. Update_at format already changed by Carbon on Model. Here you can see column

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">


<div class="table-responsive">
  <table id="tickets-table" class="table table-bordered">
    <thead>
      <tr>
        <th>Name</th>
        <th>User name</th>
        <th>Last update</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>saddsfdsafdfsafsa</td>
        <td>Sqe Begush</td>
        <td>1 hour ago</td>
      </tr>
      <tr>
        <td>testing</td>
        <td>User name</td>
        <td>8 hours ago</td>
      </tr>
      <tr>
        <td>another</td>
        <td>another user</td>
        <td>4 days ago</td>
      </tr>
      <tr>
        <td>another testing</td>
        <td>user user</td>
        <td>1 week ago</td>
      </tr>
      <tr>
        <td>another testingsss</td>
        <td>user user11</td>
        <td>1 year ago</td>
      </tr>
      <tr>
        <td>another test</td>
        <td>user userqww11</td>
        <td>4 months ago</td>
      </tr>
    </tbody>
  </table>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js">
</script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script src="//cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js"></script>
<script>
  $(document).ready(function() {
    //$.fn.dataTable.moment("YYYY/MM/DD");
    $('.table').DataTable();
  });
</script>
2

2 Answers

2
votes

The origin of the dates is unclear. If you pass moment().fromNow() yourself then just stop doing it when the display type is sort (see below). If you get already formatted data from a source you can use a library like chrono, which can parse "human dates" into "system dates":

var table = $('#tickets-table').DataTable({
  columnDefs: [
    { targets: 2,
      render: function(data, type) {
        if (type == 'sort') {
          var date = chrono.parseDate(data)
          return new Date(date).valueOf()
        } 
        return data
      }
    }
  ]
})  

demo with the <table> above -> http://jsfiddle.net/mw0c3f91/

0
votes

you have to convert the column dates to required format and then Sort the table.

moment(col[0]).fromNow();