Web Develop Wolf Web Develop Wolf - 3 months ago 12
jQuery Question

Time comparison always returns true

I have a time comparison that in an If statement that toggles a row hidden or unhidden based on what time is in the row and what time it is currently and for some reason this always returns true.

The full function is:

$(function togglePast () {
$(document)
.on('click',
'#ctl00_content_hidePast',
function (e) {
e.preventDefault();
var dt = new Date($.now() - 30 * 60000);
var time = dt.getHours() + ":" + (dt.getMinutes() < 10 ? '0' : '') + dt.getMinutes() + ":" + dt.getSeconds();
var state = $("#ctl00_content_hdnPastBookingToggle").val();
$("td.bgtime")
.each(function() {
var bookingTime = ($(this).text().split(':'));
var d = new Date();
d.setHours(+bookingTime[0]);
d.setMinutes(bookingTime[1]);

if ($(d) > time) {
var timeRow = $(this).parent();
$(timeRow).toggle("slow");
};
});
if (state === "0") {
$("#ctl00_content_hdnPastBookingToggle").val("1");
} else if (state === "1") {
$("#ctl00_content_hdnPastBookingToggle").val("0");
};
return false;
});
});


And the specific comparison that is always true is:

if ($(d) > time) {
var timeRow = $(this).parent();
$(timeRow).toggle("slow");
};

Answer

Could you please try this code:

$(function togglePast() {
  $(document)
    .on('click',
      '#ctl00_content_hidePast',
      function(e) {
        e.preventDefault();
        var dt = new Date($.now() - 30 * 60000);
        var time = dt.getHours() + ":" + (dt.getMinutes() < 10 ? '0' : '') + dt.getMinutes() + ":" + dt.getSeconds();
        var state = $("#ctl00_content_hdnPastBookingToggle").val();
        $("td.bgtime")
          .each(function() {
            var bookingTime = ($(this).text().split(':'));
            var d = new Date();
            d.setHours(+parseInt(bookingTime[0])); //converting to integer from string
            d.setMinutes(parseInt(bookingTime[1])); //converting to integer from string

            if (d > dt) {
              var timeRow = $(this).parent();
              $(timeRow).toggle("slow");
            };
          });
        if (state === "0") {
          $("#ctl00_content_hdnPastBookingToggle").val("1");
        } else if (state === "1") {
          $("#ctl00_content_hdnPastBookingToggle").val("0");
        };
        return false;
      });
});

While using the Date.setHours() you need to pass the integer value; so we are using parseInt() function

Comments