[Answered ]-Sorting DataTable by recent date

1๐Ÿ‘

โœ…

I created an example off of the data provided in your screenshot, except in my example all values other than the Dates are the same so I can demonstrate how it works.

You were pretty close, you just needed to include the following DataTables option

DataTables order option

Here:

var data = [
{
    "DateofTest": "2006-10-26",
  "OIL": "17.79",
  "WATER": "30.7",
  "GAS": "15380",
  "Gas-Lift": "5330"
},
{
    "DateofTest": "2007-05-26",
  "OIL": "17.79",
  "WATER": "30.7",
  "GAS": "15380",
  "Gas-Lift": "5330"
},
{
    "DateofTest": "2008-03-26",
  "OIL": "17.79",
  "WATER": "30.7",
  "GAS": "15380",
  "Gas-Lift": "5330"
}
];

 $(document).ready( function () {
    $('#example').DataTable({
    data: data,
    "columns" : [
    {"data":"DateofTest"},
    {"data":"OIL"},
    {"data":"WATER"},
    {"data":"GAS"},
    {"data":"Gas-Lift"}
    ],
    dom: 'B<"clear">lfrtip',
    
    // 0 is the first column it is ordering by (Date of Test)
    // 'desc' (descending) is ordering from most recent date to the oldest dates on bottom
    //'asc' (ascending) is ordering from the oldest date to the most recent on bottom
    order: [0, 'desc'],
    buttons: {
        name: 'primary',
        buttons: [ 'copy', 'csv', 'excel', 'pdf' ]
        }
      });
});
td {
  text-align: center;
}
<!DOCTYPE html>
  <html>
    <head>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jq-3.3.1/jszip-2.5.0/dt-1.11.0/b-2.0.0/b-colvis-2.0.0/b-html5-2.0.0/b-print-2.0.0/date-1.1.1/r-2.2.9/rg-1.1.3/datatables.min.css"/>
 
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/jq-3.3.1/jszip-2.5.0/dt-1.11.0/b-2.0.0/b-colvis-2.0.0/b-html5-2.0.0/b-print-2.0.0/date-1.1.1/r-2.2.9/rg-1.1.3/datatables.min.js"></script>


    </head>
    <body>
      <div class="container">
        <table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <th>Date of Test</th>
                            <th>OIL (m3/d)</th>
                            <th>WATER (m3/d)</th>
                            <th>GAS (m3/d)</th>
                            <th>Gas Lift (m3/d)</th>
                        </tr>
                    </thead>
                </table>
      </div>
    </body>
  </html>
๐Ÿ‘คBeerusDev

Leave a comment