Search code examples
javascriptjquerystringdatetablesorter

Sort date in table


I want to convert string to date in Javascript. I need to do it because I have an array and create table from that. After that I want to use Tablesorter. But it sort it only like textfield. I trying to create new parser. I have string like:

"02 January 2010"

I need to create date type from that. Is it possible in Javascript? I tried

DateFormat format = new SimpleDateFormat("dd MMMM yyyy", Locale.ENGLISH);
Date date = format.parse(s);

But it doesnt work. How would I do that?


Solution

  • With a standard date format, you can create a date parser that doesn't need to reformat the date (demo)

    $(function () {
    
        $.tablesorter.addParser({
            id: 'ddMMMMyyyy',
            is: function() {
                return false;
            },
            format: function(s) {
                var date = new Date(s);
                return date instanceof Date && isFinite(date) ? date.getTime() : s;
            },
            type: 'numeric'
        });
    
        $('table').tablesorter({
            headers : {
                5: { sorter: 'ddMMMMyyyy' }
            }
        });
    
    });