0

Onclick event is failing capturing a future date. I keep receiving the custom error message stating, "the pending date has already passed."

This feature has worked in the past, and I could've sworn it worked at the end of 2018. Not sure why it's failing now.

Button click event:

$('#markPendingSubmit').on('click', function(){
  var pendingDate = $('#reservationtime').val();
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth()+1;
  var yyyy = today.getFullYear();   
  if(dd<10) {
    dd='0'+dd
  }

  console.log(pendingDate); // <-- correct prints user selected date (which is 01/09/2019)

  if(mm<10) {
   mm='0'+mm
  }
  today = mm+'/'+dd+'/'+yyyy;

  if(pendingDate <= today)
  {
    $('#errorModal').modal('show');
    $('.message').text('The pending date you selected has already passed. Please select a future pending date.');
    return false;
  }
  else
  {
    // complete process
  }   
});

The user is attempting to set the 'pendingDate' to 1/09/2019, which is then compared to the variable 'today', but is failing because it's reading 1/09/2019 as a date that has already passed, even though today's date is 12/18/2018.

Why is this happening and how can I fix it?

halfer
  • 19,824
  • 17
  • 99
  • 186
John Beasley
  • 2,577
  • 9
  • 43
  • 89

1 Answers1

0

This is how I solved my problem:

if(new Date(pendingDate) <= new Date(today))
{
  $('#errorModal').modal('show');
  $('.message').text('The pending date you selected has already passed. Please select a future pending date.');
  return false;
}

Thus, both 'pendingDate' and 'today' are ensured to be Date objects, and therefore can be compared in an if/else statement.

Such a simple fix.

John Beasley
  • 2,577
  • 9
  • 43
  • 89
  • 2
    Note that this is risky, due to the differences in date parsing methods across browsers. See the answers to [Why does Date.parse give incorrect results?](https://stackoverflow.com/q/2587345/215552) – Heretic Monkey Dec 18 '18 at 16:22
  • @HereticMonkey - thank you for the input. I will take it into consideration. – John Beasley Dec 18 '18 at 16:57