Anna Jeanine
Anna Jeanine

Reputation: 4125

Comparing new Date in JavaScript fails

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.

Upvotes: 2

Views: 181

Answers (2)

Felix Haeberle
Felix Haeberle

Reputation: 1606

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"/>

Upvotes: 1

nicholaswmin
nicholaswmin

Reputation: 22949

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");
}

Upvotes: 1

Related Questions