wulinworks
wulinworks

Reputation: 21

jQuery Tablesorter is not working with date

My code:

<th class="sorter-shortDate">Date</th> $('table').tablesorter({dateFormat: "yyyymmdd"});

Sorting is working on numbers, but it is not working on dates, My date format is y-m-d H:i, I also tried to add custom parser:

$.tablesorter.addParser({
    id: "customDate",
    is: function(s) {
          return false;
          //use the above line if you don't want table sorter to auto detected this parser
          //else use the below line.
          //attention: doesn't check for invalid stuff
          //2009-77-77 77:77:77.0 would also be matched
          //if that doesn't suit you alter the regex to be more restrictive
          //return /\d{1,4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}/.test(s);
    },
    format: function(s) {
          s = s.replace(/\-/g," ");
          s = s.replace(/:/g," ");
          s = s.replace(/\./g," ");
          s = s.split(" ");
          return $.tablesorter.formatFloat(new Date(s[0], s[1]-1, s[2], s[3]).getTime()+parseInt(s[6]));
    },
    type: "numeric"
});

Can anyone help me please?

Upvotes: 2

Views: 144

Answers (1)

Mottie
Mottie

Reputation: 86413

There's a minor bug in the shortDate parser; it replaces all . with a / while converting the date into something the built-in JS date parser can understand (e.g. 2009-12-31 08:09:10.1 becomes 12/31/2009 08:09:10/1 - that last decimal place getting changed into a slash is breaking everything.

You can get around this by modifying the short date parser's regular expression - demo

$.tablesorter.regex.shortDateReplace = /-/g;

$(function() {
  $('table').tablesorter({
    theme: 'blue',
    dateFormat: 'yyyymmdd'
  });
});

Upvotes: 1

Related Questions