Search code examples
jquerysortingtablesorter

tablesorter sort by date period / date format dd.mm.yyyy - dd.mm.yyyy


I have the following table:

    <?php 
    $reqSQL = "SELECT * FROM data_cursanti , clients WHERE  start_course > DATE_SUB(now(), INTERVAL 12 MONTH) ORDER BY data_cursanti.name ASC ";
    $result = mysqli_query($conexiune, $reqSQL) or die("Error: " . mysqli_error($conexiune)); // sql query for results than the table
    $counter = 1; // for rows counting
    echo '<table id="users" class="tablesorter">
    <thead>
    <tr>
    <th width="3%">No.</th>
    <th width="15%">Name</th>
    <th width="10%">Company</th>
    <th width="7%">Course</th>
    <th width="10%">Course Period</th>
    </tr>
    </thead>
    <tbody>'
    while ($row = mysqli_fetch_array($result)) {
    $date1 = date('d.m.Y', strtotime($row['start_course']));
    $date2 = date('d.m.Y', strtotime($rand['end_course']));
    echo
    '<tr>
    <td width="3%">'.$counter.'</td>
    <td width="15%">'.$row['name'].'</td>
    <td width="10%">'.$row['company_name'].'</td>
    <td width="7%">'.$row['course_type'].'</td>
    <td width="10%">'.$date1.' - '.$date2.'</td>
    </tr>'
    $counter++;
    } //end while loop
    echo '</tbody>
    </table>'; //close table

and using the following parser (slightly modified from here:How to sort date with jquery tablesorter which is in format 'dd/mm/yyyy - dd/mm/yyyy') for tablesorter to sort by my course period column (the column uses date format dd.mm.yyyy - dd.mm.yyyy):

$(function() {

    $.tablesorter.addParser({
        id: "date-range",
        is: function(){
            return false;
        },
        format: function(s, table, cell) {

            var dates = s.replace(/(\d{1,2})[\/\.](\d{1,2})[\/\.](\d{4})/g, "$2/$1/$3").split(' - '),
                parsed = [];
            if (dates.length) {
                $.each(dates, function(i,d){
                    var v = new Date(d);
                    parsed.push($.type(v) === 'date' ? v.getTime() : d);
                });
            }
            return parsed.length ? parsed.join('') : s;
        },
        parsed : true,
        type: "text"
    });

// and calling the parser after this script like this: 


    $(function() {
$("#users")
.tablesorter({widthFixed: true, widgets: ['zebra'],  headers: {0: {sorter: false}, 4 : { sorter: 'date-range' }, {sortForce: [[0,0]]})
.tablesorterPager({container: $("#pager"), size: 20});
});

the problem is that the table gets sorted by dd (day) part of the first date, instead of month as I would like it to be!. Any ideas? What am I doing wrong? Could somebody please modify my code to sort the table data by the mm (month) value of the first date? I have like almost zero knowledge of javascript ... Thankyou!

LE: Also I tried to use the solution presented by mottie in the first answer but the table just breaks down and won't sort anything when I add the 4 : { sorter: 'date-range' } piece of code in the script.


Solution

  • The problem is that the dates in this question are separated by periods and the regexp for the other question was using regex which only looked for forward slashes or spaces (demo).

    This regexp will work with mm-dd-yyyy dates separated by "-", "/", "." or "" (spaces).

    var dates = s.replace(/(\d{1,2})[-./\s](\d{1,2})[-./\s](\d{4})/g, "$2/$1/$3").split(' - ')
    

    Also, the sorter setting needs to target the last row:

    $("table").tablesorter({
        headers: {
            4: {
                sorter: 'date-range'
            }
        }
    });