Search code examples
javascriptjquerydatatablesyadcf

jQuery DataTables yadcf greater-than-equal to (date)


I am using the jQuery YADCF plugin to filter out a column of dates formatted mm-dd-yyyy. The plugin works beautifully out of the box, except it only shows an EXACT match on the dates. It will show me 03/06/2016 if that exact row is in the table, but I really want it to show 03/06/2016 and all dates after.

I have been trying to do this manually with DataTables and there's no real working or well-documented jQuery DataTables version out there that does a "greater than and equal to" date search.

Has anyone successfully done this with YADCF (or DataTables solo)?


Solution

  • My use case here was an edge case for YADCF, so I repurposed some code from http://codepen.io/markmichon/pen/tmeGD to get my filter working. I didn't use YADCF this time, but great to know it's out there. Big shout-out to Daniel, the plugin author, for responding to me!!

    // converts date strings to a Date object, then normalized into a YYYYMMMDD format (ex: 20131220). Makes comparing dates easier. ex: 20131220 > 20121220
    var normalizeDate = function(dateString) {
        var date = new Date(dateString);
        var normalized = date.getFullYear() + '' + (("0" + (date.getMonth() + 1)).slice(-2)) + '' + ("0" + date.getDate()).slice(-2);
        return normalized;
    }
    
    var filterByDate = function(column, vesselDate) {
    // Custom filter syntax requires pushing the new filter to the global filter array
        $.fn.dataTableExt.afnFiltering.push(
            function( oSettings, aData, iDataIndex ) {
                var rowDate = (aData[column]).replace(/<(?:.|\n)*?>/gm, '').match(/[0-9][0-9]\/[0-3][0-9]\/[0-9][0-9][0-9][0-9]/), // take my mm-dd-yyyy – timestamp format wrapped in hTML and strip it down to the mm-dd-yyy only
              start = normalizeDate(vesselDate); // use a normalized date (see code below)
              rowDate = normalizeDate(rowDate);
          // If our date from the row is between the start and end
          if (start <= rowDate) {
            return true;
          } else if (rowDate >= start && start !== ''){
            return true;
          } else {
            return false;
          }
        }
        );
    };
    
    $('#dateStart').on('change keyup', function(){
        dateStart = $(this).val();
        filterByDate(3, dateStart); //passing the column value to the function
        $vesselSchedule.draw(); //updating the table
    });
    
    $('#dateEnd').on('change keyup', function(){
        dateEnd = $(this).val();
        filterByDate(4, dateEnd);
        $vesselSchedule.draw();
    });
    

    https://www.nwseaportalliance.com/operations/vessels#/ for a live example.