0

I am trying to hide a range of div elements that do not match a set date () after iterating through a set. But as the dates are in two different formats, I need to convert them to one standard format before making the comparison. Unfortunately, this is not working, although the dates match, all of the div elements are hidden. Does anybody know what is going wrong? Thanks.

Jsfiddle: http://jsfiddle.net/ss308rwa/

HTML

<input type="text" class="form-control date" value="04/06/2015">
<button type="button" class="btn btn-primary" id="search-button">Search</button>
<div class="rideshare-item" data-date="2015-06-04">04/06/2015</div>
<div class="rideshare-item" data-date="2015-06-05">05/06/2015</div>

JS

$('body').on('click', '#search-button', function (event) {
    var date = $('.date').val().trim();
    $('.rideshare-item, .no-result').hide();
    $('.rideshare-item').each(function (a, b) {
        var rideshareDate = $(b).data('date');
        if (date.length == 0) {
            $(this).closest('.rideshare-item').show();
        } else if (date.length > 0) {
            var timestamp = Date.parse(date)
            if (isNaN(timestamp) == false) {
                if (parseDateEntry(date) == parseDateAttribute(rideshareDate)) {
                    $(this).closest('.rideshare-item').show();
                }
            }
        }
    });
});

function parseDateEntry(input) {
    var parts = input.split('/');
    // new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
    return new Date(parts[2], parts[1] - 1, parts[0]);
}

function parseDateAttribute(input) {
    var parts = input.split('-');
    // new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
    return new Date(parts[0], parts[1] - 1, parts[2]);
}
methuselah
  • 12,766
  • 47
  • 165
  • 315
  • in the input box only one date can be specified right? if yes how can a "date range" be hidden if the user specifies only one date.. – Lucky May 01 '15 at 17:51
  • This [answer](http://stackoverflow.com/a/14629978/2030565) explains why `parseDateEntry(date) == parseDateAttribute(rideshareDate)` fails. – Jasen May 01 '15 at 18:19

1 Answers1

2

change parseDateEntry(date) == parseDateAttribute(rideshareDate)

to parseDateEntry(date).getTime() == parseDateAttribute(rideshareDate).getTime()

will work.

Surely
  • 1,649
  • 16
  • 23
  • comparing Date object seems always return false, even though the time is at the same point. "var a = new Date();var b = new Date(a.getTime());a==b" returns false. – Surely May 01 '15 at 17:34