JQuery Datepicker: If selected date is today's date

孤街浪徒 提交于 2019-12-10 15:53:02

问题


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?


回答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.




回答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');
  }
});



回答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.




回答4:


getTime() returns milliseconds, instead compare the day month and year, which I believe a normal date comparison does(maybe wrong). See: http://www.w3schools.com/js/js_obj_date.asp



来源:https://stackoverflow.com/questions/9946232/jquery-datepicker-if-selected-date-is-todays-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!