1

I want to compare the picked date with the current date. But the if always falls thru to else. I read a couple of posts that the if will always return false because the two dates are two diffretnt object but contains the same time. I tried getTime() but didnt get it to work either. What i want to achive in the end with this comparison is I want to restrict date input after 09:30 in the morning (24h) if the picked date is today. Is this the right way to go? To filter out the date first and then the time of day? Appriciate all the help I can get! I couldnt get the JSFiddle to work. wanted to give a live sample.

  $('#startDatePicker').datepicker({

  var fromDate = $('#startDatePicker').datepicker('getDate');
  var today = new Date();
  today.setHours(0, 0, 0, 0).getTime();
  selectedDate.setHours(0, 0, 0, 0).getTime();

  if (today === fromDate ) {
    alert("Today")

  } else {


  };
});
4
  • selectedDate comes from nothing ..? Commented Jul 5, 2017 at 8:04
  • 2
    Possible duplicate of Compare two dates with JavaScript Commented Jul 5, 2017 at 8:05
  • Sorry.@Teemu. Fixed it. Commented Jul 5, 2017 at 8:29
  • Thanks!! @jajasuperman. Apperantly i didnt search hard enough. Commented Jul 5, 2017 at 8:40

1 Answer 1

1

Is that jQuery UI's datepicker? If yes, then you need to add onSelect as a property to your datepicker parameter.

$('#startDatePicker').datepicker({
  onSelect: function (selectedDate) {
    var today = new Date().setHours(0, 0, 0, 0);
    var selected = new Date(selectedDate).getTime();

    if (today === selected) {
      alert('Today');
    } else {
      // Do something.
      console.log(selected);
    }
  }
});

$(function () {
  $('#startDatePicker').datepicker({
    onSelect: function (selectedDate) {
      var today = new Date().setHours(0, 0, 0, 0);
      var selected = new Date(selectedDate).getTime();
      
      if (today === selected) {
        alert('Today');
      } else {
        // Do something.
        console.log(selected);
      }
    }
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input type="text" id="startDatePicker" />

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.