Search code examples
javascriptjquerysortingtablesorter

Incorrect sorting date / time with jquery tablesorter


i'm using plugin Tablesorter. I can not properly configure sort one of the columns. It looks like this (days hours minutes):

0d04h11m
4d22h26m
27d20h14m
0d09h50m
2d02h34m
1d11h02m

I tried to apply {sorter:'digits'}

After sorting:

4d22h26m
2d02h34m
27d20h14m
1d11h02m
0d09h50m
0d04h11m

That is not true sorts, if the two-digit days.

How can I solve this problem?


Solution

  • UPDATED

    You can use this funcition to sort your dates:

    $(function() {
      var sortDates = (function(){
        function dateToNumber(date){
          return parseInt(
            date.match(/\d+/g)
              .map(function(field){
                return field.length === 1 ? '0' + field : field;
              }).join('')
          , 10);
        }
        return function(date1, date2){
          return dateToNumber(date1) - dateToNumber(date2);
        };
      }());
    
      $("#table").tablesorter({
        textSorter : {
          1 : sortDates
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.25.1/js/jquery.tablesorter.min.js"></script>
    
    <table id="table">
      <thead>
        <tr>
          <th>dates</th>
        </tr>
      </thead>
      <tr>
        <td>0d04h11m</td>
      </tr>
      <tr>
        <td>4d22h26m</td>
      </tr>
      <tr>
        <td>27d20h14m</td>
      </tr>
      <tr>
        <td>0d09h50m</td>
      </tr>
      <tr>
        <td>2d02h34m</td>
      </tr>
      <tr>
        <td>1d11h02m</td>
      </tr>
    </table>