2

I'm trying to develop a custom date range filter for a dataTables. The user can enter a start date and an end date in two inputs and filter the whole table.

When entering a beginning and end date, the results match. When I enter only one of the two, the results fail. For example; the start date is 12/01/2017 but I can see instances with the date 29-11-2016... My code for the filtering:

$('#filter').on('click', function(e) {
            e.preventDefault();
            var startDate = $('#start').val(),
                endDate = $('#end').val();

            filterByDate(10, startDate, endDate); // We call our filter function

            $dTable.dataTable().fnDraw(); // Manually redraw the table after filtering
        });

        var filterByDate = function(column, startDate, endDate) {
            $.fn.dataTableExt.afnFiltering.push(
                function( oSettings, aData, iDataIndex ) {
                    var rowDate = normalizeDate(aData[10]),
                        start = normalizeDate(startDate),
                        end = normalizeDate(endDate);


                    // If our date from the row is between the start and end
                    if (start <= rowDate && rowDate <= end) {
                        console.log(start <= rowDate);
                        return true;
                    } else if (rowDate >= start && end === '' && start !== ''){
                        console.log(rowDate >= start && end === '' && start !== '');
                        return true;
                    } else if (rowDate <= end && start === '' && end !== ''){
                        return true;
                    } else {
                        return false;
                    }
                }
            );
        };

        var normalizeDate = function(dateString) {
            var date = new Date(dateString);
            var normalized = ("0" + date.getDate()).slice(-2) + '/'+ (("0" + (date.getMonth() + 1)).slice(-2)) + '/' +date.getFullYear() ;
            return normalized;
        };

Could some JavaScript genius help me to get the comparison of rowData >= start.... and rowDate <= end.... working correctly? The input dates are separated by / and in my table by /, but the normalizeData function makes them the same layout.

Anna Jeanine
  • 3,975
  • 10
  • 40
  • 74
  • What is the value of *dateString*? Please consider [*Why does Date.parse give incorrect results*](http://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) before using the Date constructor to parse strings. – RobG Apr 25 '17 at 23:06

2 Answers2

1

Here's an idea:

Convert your dates to Unix timestamps and compare those instead. You can use date.getTime() to do this conversion.

As slezica said on the comment below:

getTime() returns the amount of milliseconds since January 1, 1970, 0 hours. It's a simple number you can compare.

Example:

var date1 = new Date(1995, 11, 17);
var date2 = new Date(2005, 12, 25);

if (date2.getTime() > date1.getTime()) {
  console.log("date 2 is later than date 1");
}
nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
1

You can use the following to compare the two dates!

In this example you use the UNIX timestamp to compare the two dates.

if ((new Date(startDate).getTime() > new Date(endDate).getTime())) { 
  // start date is greater than end date
}

if ((new Date(startDate).getTime() < new Date(endDate).getTime())) { 
  // start date is lower than end date
}

Working snippet:

var startDate = document.getElementById('start').value;
var endDate = document.getElementById('end').value;

if ((new Date(startDate).getTime() > new Date(endDate).getTime())) {
  console.log("start date is greater than end date")
}

if ((new Date(startDate).getTime() < new Date(endDate).getTime())) {
  console.log("start date is lower than end date")
}
<input id="start" value="10/10/2017"/>
<input id="end" value="12/10/2017"/>
Felix Haeberle
  • 1,530
  • 12
  • 19
  • Please do not recommend parsing strings with the Date constructor, it's problematic at best. A real parser should be used, either a library or simple (maybe 3 line) function. The value returned by *getTime* is a [*time value*](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-time-values-and-time-range), which is milliseconds. A "UNIX timestamp" is seconds, though it uses the same epoch as ECMAScript (which is shared by many systems and languages, such as Java). – RobG Apr 25 '17 at 23:08
  • 1
    I know the problem, I will later update the answer and .split() the string and after go for the Date.. Thanks for the advice:) – Felix Haeberle Apr 25 '17 at 23:34