Ensuring a date is at least 1 day later than another date using jQuery UI Datepicker

我的梦境 提交于 2019-12-13 02:53:00

问题


Using jQuery DatePicker, I'd like to ensure that the departure date is at least 1 day after the arrival date. The closest I've managed to get to this is to ensure that the departure date is on the same day as the arrival date (I just couldn't figure out how to add 'selectedDate + 1 day' in the JS). I'd appreciate any help with this, thanks.

Here's my 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 );
  }
});

Here's my 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:


You can pass the datepicker object in the onClose method:

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

Consequently, this should work fine:

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

Fiddle:

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

Credit for the padding idea comes from the accepted answer by user113716 in this thread:

Javascript add leading zeroes to date



来源:https://stackoverflow.com/questions/16107787/ensuring-a-date-is-at-least-1-day-later-than-another-date-using-jquery-ui-datepi

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