JQuery Datepicker: If selected date is today's date

21,514

Solution 1

The string "30/03/2012" when used to create a date results in a Date object that represents midnight on the 30 March 2012. When you call new Date() it creates a Date object that represents the current time (including seconds and milliseconds).

You'll need to set the hour, minute, second and millisecond properties of your Date object to 0 so that they represent the exact same time, using the setHours(), setMinutes(), etc functions.

For more information about the Date object take a look at the MDN entry.

Solution 2

The datepicker object has a getDate method you can use that returns a date value to compare it to a new date(). You do have to some further massaging on the new date, but this should get you what you want.

JsFiddle Example

HTML:

Date: <input type="text" id="thedate"/>
<div id="checkDate">Check Date</div>

JS:

$('#thedate').datepicker();

$('#checkDate').bind('click', function() {
  var selectedDate = $('#thedate').datepicker('getDate');
  var today = new Date();
  today.setHours(0);
  today.setMinutes(0);
  today.setSeconds(0);
  if (Date.parse(today) == Date.parse(selectedDate)) {
    alert('today!');
  } else {
    alert('not today');
  }
});

Solution 3

You need to make sure you're comparing apples to apples. Here's an easy way to check:

jQuery:

$('#dp').datepicker({
    onSelect: function(dateText) {
        var today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime();
        var selected = new Date(dateText).getTime();
        if (today > selected) alert('prior to today');
        else if (today < selected) alert('after today');
        else alert('today');
    }
});​

jsFiddle example.

Share:
21,514
Bad Programmer
Author by

Bad Programmer

A self-taught PHP programmer.

Updated on August 10, 2021

Comments

  • Bad Programmer
    Bad Programmer over 2 years

    I am able to determine if the selected date is in the past by using:

    var due_date = $('#due_date').val();
    if(new Date(due_date).getTime() <  new Date().getTime())
    {
      //do stuff
    }
    

    ^This works fine

    I am using the following to determine if a selected date is today's date:

    var due_date = $('#due_date').val();
    var today = new Date().getTime();
    if(new Date(due_date).getTime() == today)
    {
        alert('ok');
    }
    

    But it's not hitting that alert. What is wrong with the above statement?

  • Asha
    Asha almost 6 years
    hi, i have used jqueryui.com/datepicker date picker and i need to check the selected date is today or not. i used your code but its not showing either answer nor datepicker