jQuery DatePicker - dates have to be one day apart, but there's a bug if the start date is tomorrow

会有一股神秘感。 提交于 2019-12-24 22:43:02

问题


I'm using jQuery DatePicker to ensure that a departure date is at least 1 day after an arrival date. I got the code to do this from this question.

However, I've just noticed that if I choose tomorrow (31st May 2013) as the arrival date, the departure date gets set to 10th January 2019! But if I pick an arrival date after tomorrow, it seems to work fine. Any ideas on what's going wrong with this? Thanks for any help.

Here's a JSFiddle with the code that shows the issue.

And here's the JS itself:

$(".datepicker_arrival").datepicker({
  dateFormat: 'dd/mm/yy',
  minDate: new Date(),
  onSelect: function(dateText, inst) {
    if($('.datepicker_departure').val() == '') {
      var current_date = $.datepicker.parseDate('dd/mm/yy', dateText);
      current_date.setDate(current_date.getDate()+1);
      $('.datepicker_departure').datepicker('setDate', current_date);
    }
  },
  onClose: function( selectedDate, test) {
     var  MyDateString = ('0' + (parseInt(test.selectedDay)+1)).slice(-2) + '/'
             + ('0' + (test.selectedMonth+1)).slice(-2) + '/'
             + test.selectedYear;
      $( ".datepicker_departure" ).datepicker( "option", "minDate", MyDateString);
  }
});

$(".datepicker_departure").datepicker({
  dateFormat: 'dd/mm/yy',
  minDate: new Date(),
  onClose: function( selectedDate ) {
    $( ".datepicker_arrival" ).datepicker( "option", "maxDate", selectedDate );
  }
});

回答1:


Okay to summarize the solution in the comments (which was provided by me, I'm not just leeching an answer).

The error was caused by this piece of code:

var  MyDateString = ('0' + (parseInt(test.selectedDay)+1)).slice(-2) + '/'
             + ('0' + (test.selectedMonth+1)).slice(-2) + '/'
             + test.selectedYear;

which was not correctly adding a day to the date. When adding the day, the months were not taken into account, so any end of the month caused a date like so to be created:

32/05/2013

Of course there is no 32nd of the month.

Therefore, a suggested fix code can be found here:

jsfiddle.net/9mSxk/3



来源:https://stackoverflow.com/questions/16854506/jquery-datepicker-dates-have-to-be-one-day-apart-but-theres-a-bug-if-the-sta

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