Search code examples
phpjquerysortingtablesorter

How to sort both strings and dates with tablesorter jquery plugin?


I've got some trouble to deal with when it comes to sort some datas in my table (string datas). I take dates from my database, and format them like this :

    $change['ProposedDate'] = date('d/m/Y',strtotime($r['ProposedDate']));

(note that I also tried :

    $change['ProposedDate'] = (string)date('d/m/Y',strtotime($r['ProposedDate']));

)

and I use this to transform into "None"

if($change['ProposedDate'] == "30/11/-0001")
{
    $change['ProposedDate'] ="None";
}

The table is like this (after PHP transformed $c['ProposedDate'] into "XX/YY/ZZZZ" in the HTML source code):

<table>
 <thead>
  <tr>
   <th> ID </th>
   <th> Proposed Date</th>
   <th> Suggested Date</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>1</td>
   <td>01/10/2014</td>
   <td>None</td>
  </tr>
  <tr>
   <td>2</td>
   <td>14/10/2014</td>
   <td>10/12/2014</td>
  </tr>
  <tr>
   <td>3</td>
   <td>None</td>
   <td>09/09/2014</td>
  </tr>
 </tbody>
</table>

The thing I can't understand, is that I'm able to sort strings such as "14-0214-98","13-0101-01" and "14-0102-40" , or "Current", "Waiting", "New" and "Submitted". But I can't sort dates. I've "None" between two lines containing dates. I tried many solutions, such as using empty strings "" to replace "None", or using "a" to replace "None", but nothing worked.

Does anyone has any idea to get rid of this problem ?

NB : It's not any problem for me to transform dates into strings, I'll transform back them later anyway (to transform "None" to "30/11/-0001" for example). So if you have a solution working with string, I'll take it !

Thanks people, i'm really desesperate :(


Solution

  • I am guessing that the first column might contain "None" instead of a date, this would cause the plugin to detect regular text instead of a date for that column. So you'll need to set the parser specifically for a date.

    I'm not sure why version of tablesorter you're using, so here is how you can do it:

    1. Original tablesorter (demo):

      $('table').tablesorter({
      
          dateFormat : "uk",
      
          headers: {
              // set "sorter: false" (no quotes) to disable the column
              0: { sorter: "text" },
              1: { sorter: "shortDate" },
              2: { sorter: "shortDate" }
          }
      
      });
      
    2. My fork of tablesorter (demo):

      $('table').tablesorter({
          theme: 'blue',
      
          // other options: "mmddyyyy" & "yyyymmdd"
          dateFormat: "ddmmyyyy",
      
          headers: {
              // set "sorter: false" (no quotes) to disable the column
              0: { sorter: "text" },
              1: { sorter: "shortDate" },
              2: { sorter: "shortDate" }
          }
      
      });