使用jQuery UI Datepicker确保日期比另一个日期晚至少1天

时间:2013-04-19 15:09:09

标签: jquery-ui jquery-ui-datepicker

使用jQuery DatePicker,我想确保出发日期是抵达日期后至少1天。我设法得到的最接近的是确保出发日期与到达日期在同一天(我无法弄清楚如何在JS中添加'selectedDate + 1天')。我很感激任何帮助,谢谢。

这是我的JS:

$(".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 ) {
    $( ".datepicker_departure" ).datepicker( "option", "minDate", selectedDate );
  }
});

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

这是我的HTML:

<input type="text" name="arrival" class="datepicker datepicker_arrival textfield" placeholder="Arrival Date" />

<input type="text" name="departure" class="datepicker datepicker_departure textfield" placeholder="Departure Date" />

1 个答案:

答案 0 :(得分:2)

您可以在onClose方法中传递datepicker对象:

<强> http://api.jqueryui.com/datepicker/#option-onClose

因此,这应该可以正常工作:

$(".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);
  }
});

小提琴:

http://jsfiddle.net/SpAm/9mSxk/1/

填充构思的信用来自user113716在此主题中接受的答案:

<强> Javascript add leading zeroes to date