jquery tablesorter sort date dd mmm yyyy

旧城冷巷雨未停 提交于 2019-12-31 05:42:08

问题


I am pretty new to tablesorter but I have a table with several columns, and the 3rd column is dates, coming back from the DB in the form of dd mmm yyyy, hh:mm:ss (am/pm)

For example

29 Jul 2013, 1:12:23 PM
2 Aug 2013, 3:59:59 PM
17 Jul 2013, 09:30:00 AM

then I sort my table

$(document).ready(function() 
    { 
        $("#myTable").tablesorter({sortInitialOrder: "desc"}); 
    } 
); 

but it comes out in "alphabetical order", meaning 29 before 2 before 17, not taking into account the date aspects.

It looks like there is a dateFormat option I can pass in but I can't get it to work. I know Java has special keys with different meanings like this. Is there anything comparable in tablesorter? How do I go about making sure the one date column is sorted properly?

I can guarantee that the format will always be as I specified above, and I don't want to change the appearance of the displayed date, just the sorting functionality.

Looks like dateFormat: 'usLongDate' is close to what I need but not working

UPDATE: I think my problem is that I have more info in the object than just the date, however I want to sort by just the date. Here is my working jsFiddle.


回答1:


Try this parser (it's not perfect since it doesn't validate the date, i.e. it will accept a time of 99:99:99; but then the date parser will return an invalid date and default back to plain text (demo):

$.tablesorter.addParser({
    id: "date",
    is: function (s) {
        return false;
    },
    format: function (s, table) {
        var date = (s + '').match(/(\d{1,2}\s+\w{3}\s+\d{4}),(\s+\d{1,2}:\d{1,2}:\d{1,2}\s+[AP]M)/);
        return date ? new Date(date[1] + date[2]).getTime() || s : s;
    },
    type: "numeric"
});

Update: To elaborate on the regex and answer your comment... basically the regex is matching a pattern: \d{1,2} matches any 1 or 2 digits, \d{4} matches any 4 digits, \w{3} matches any "word" 3 letters in length, \s+ matches any number of spaces or tabs and [AP]M matches AM or PM.

Now the parenthesis () save specific matches - notice that the comma is outside of the parentheses. And note that the first value in the array is the entire string, if it matches. So the first part date[1] contains the date portion (e.g. 29 Jul 2013) and the second part date[2] contains the time (e.g. 1:12:23 PM).

Check out this basic tutorial on regular expressions, then try messing around with this regex tester.



来源:https://stackoverflow.com/questions/18088495/jquery-tablesorter-sort-date-dd-mmm-yyyy

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