sort date field with tablesorter

↘锁芯ラ 提交于 2019-12-11 01:43:46

问题


I'm using the JQuery tablesorter plugin. The table has a column that shows dates in the format 05 Mar 2012. The tablesorter plugin seems to treat this column as text, because it sorts it in the order

  • 05 Mar 2012
  • 06 Jan 2012
  • 07 Dec 2012

How can I sort these dates in chronological order instead?


回答1:


Parse the date string to a Date, then convert it to milliseconds. Let tablesorter sort the column as numeric.

$.tablesorter.addParser({ 
    id: 'my_date_column', 
    is: function(s) { 
        // return false so this parser is not auto detected 
        return false; 
    }, 
    format: function(s) { 
        var timeInMillis = new Date.parse(s);
        return timeInMillis;         
    }, 
    // set type, either numeric or text 
    type: 'numeric' 
}); 

$(function() { 
    $("table").tablesorter({ 
        headers: { 
            6: {       // Change this to your column position
                sorter:'my_date_column' 
            } 
        } 
    }); 
});

If you have trouble with Date.parse, see my answer to this question.




回答2:


You can also add a hidden span tag before your date in numerical format (yyyymmdd). This text will come first and be used for sorting but it will be hidden from sight and only show the format you want.

    <td><span style="display:none">20130923</span>23rd September 2013</td>



回答3:


You will need to use addParser method and create a parser that converts your string to date object.

follow example on plugin site http://tablesorter.com/docs/example-parsers.html

If need a date parser:

http://www.datejs.com/

EDIT: your dates convert easily in format shown:

 console.log(new Date('05 Mar 2012'))//  logs proper date object



回答4:


Haven't used tablesorter in a while but I seem to remember having a similar issue with UK dates.

You can add a dateformat parameter to the tablesorter plugin with your custom dateformat.

dateFormat: 'dd MMM yyyy' 


来源:https://stackoverflow.com/questions/9568473/sort-date-field-with-tablesorter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!