Solution #2 for sorting date columns in jQuery DataTable

by Saurabh Misra

HTML

<!DOCTYPE html>
<html>

  <head>
    <title>Basic DataTable setup</title>
    
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    
    <!-- Moment.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>
    
    <!-- DataTables.js -->
    <link href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css" rel="stylesheet">
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
  </head>

  <body>
    <table class="table stripe my-table">
      <thead>
        <tr>
          <th>Name</th>
          <th>Email</th>
          <th>Date Registered</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Saurabh Misra</td>
          <td>saurabh@example.com</td>
          <td>2023-10-22</td>
        </tr>
        <tr>
          <td>Arpita Misra</td>
          <td>arpita@example.com</td>
          <td>2023-10-03</td>
        </tr>
        <tr>
          <td>Nandini Misra</td>
          <td>nandini@example.com</td>
          <td>2023-10-25</td>
        </tr>
      </tbody>
    </table>
  </body>

</html>

JavaScript

$(document).ready(function() {
  $("table.my-table").DataTable({
    columnDefs: [{
      target: 2,
      render: DataTable.render.datetime("D MMM, YYYY")
    }],
    order: [
      [2, 'desc']
    ]
  });
});