Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Datepicker: If selected date is today's date

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?

like image 529
Bad Programmer Avatar asked Mar 30 '12 15:03

Bad Programmer


People also ask

How to auto select today date in datepicker?

To set current date in control to which jQuery UI datepicker bind, use setDate() method. Pass date object which needs to be set as an argument to setDate() method. If you want to set it to current date then you can pass 'today' as argument.

How to select current date in jQuery datepicker?

You must FIRST call datepicker() > then use 'setDate' to get the current date. $(". date-pick").

What is datetimepicker in jQuery?

A date-picker of jQuery UI is used to provide a calendar to the user to select the date from a Calendar. This date picker usually connected to a text-box so user selection of date from the calendar can be transferred to the textbox.


2 Answers

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');
  }
});
like image 179
aztechy Avatar answered Sep 29 '22 11:09

aztechy


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.

like image 31
Anthony Grist Avatar answered Sep 29 '22 12:09

Anthony Grist