Home > Mobile >  DataTables date range filter, not getting the first date
DataTables date range filter, not getting the first date

Time:04-02

Hi I am using DataTables date range filter. here is the link -> enter image description here

But when i enter 03-31-2022 to 04-02-2022 it showing me the record of 04-01-2022 enter image description here

CodePudding user response:

It looks like you're setting MinDate and MaxDate once, on document.ready, but not after the user enters dates.

I've moved the code that sets MinDate and MaxDate into your search filter.

Another potential problem is that you're comparing dates in MM-DD-YYYY format as if they are strings, and this won't work when comparing, say, 03-12-2022 with 05-12-2020. The first date is later from a date perspective, but earlier (first) from a string-comparison perspective. So you should probably be converting dates to YYYY-MM-DD format, which works for string comparison.

I'm not sure about this last part because you have new Date(...) (which is standard JS) as well as new DateTime(...) (which I don't think is standard JS) so it's not really clear whether you're comparing strings (e.g. minDate.val()) or objects (e.g. new Date( data[9] )).

var minDate, maxDate;
 
// Custom filtering function which will search data in column four between two values
$.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        // Create date inputs
        minDate = new DateTime($('#min'), {
            format: 'MM-DD-YYYY'
        });
        maxDate = new DateTime($('#max'), {
            format: 'MM-DD-YYYY'
        });

        var min = minDate.val();
        var max = maxDate.val();
        var date = new Date( data[9] );
 
        if (
            ( min === null && max === null ) ||
            ( min === null && date <= max ) ||
            ( min <= date   && max === null ) ||
            ( min <= date   && date <= max )
        ) {
            return true;
        }
        return false;
    }
);
 
$(document).ready(function() {
    $('#sales').DataTable({
        aLengthMenu: [
            [25, 50, 100, 200, -1],
            [25, 50, 100, 200, "All"]
        ],
        iDisplayLength: -1,
        scrollX: true
    });
 
    // DataTables initialisation
    var table = $('#sales').DataTable();
 

    // Refilter the table
    $('#min, #max').on('change', function () {
        table.draw();
    });
});
  • Related