Jquery datepicker日期范围为365天

时间:2015-11-20 10:27:31

标签: jquery datepicker jquery-ui-datepicker

我试图在jquery datepicker中限制日期范围。实际上我有日期范围输入,如from_date和to_date我想to_date maxdate值应该是from_date + 365天所以它将是1年的日期范围。我不知道该怎么做。

我试过这种方式但没有工作:

$(function() {
    $( "#from" ).datepicker({
      defaultDate: "+1w",
      minDate: 0,
      changeMonth: true,
      numberOfMonths: 1,
      onClose: function( selectedDate ) {
        $( "#to" ).datepicker("option", "minDate", selectedDate );
      }
    });
    $( "#to" ).datepicker({
      defaultDate: "+1w",
      changeMonth: true,
      numberOfMonths: 1,
      maxDate: new Date($('#from').val() + 365),
    });
  }); 

2 个答案:

答案 0 :(得分:0)

您可以在days_to_add中设置所需的天数。另请注意,您可能需要changeYear选项。



$(function () {
    $("#from").datepicker({
        defaultDate: "+1w",
        minDate: 0,
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        onClose: function (selectedDate) {
            $("#to").datepicker("option", "minDate", selectedDate);

            var days_to_add = 365, // SET DAYS HERE
                parsed_date = new Date($.datepicker.parseDate('mm/dd/yy', selectedDate)),
                add_year = new Date(parsed_date.setDate(parsed_date.getDate() + days_to_add)),
                formatted_date = $.datepicker.formatDate('mm/dd/yy', add_year);

            $('#to').datepicker('option', 'maxDate', formatted_date);
        }
    });
    $("#to").datepicker({
        dateFormat: 'mm/dd/yy',
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        maxDate: '+1y'
    });
});

<link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>

<input id="from" />
<input id="to" />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以这样做

$("#from").datepicker({
dateFormat: 'dd/mm/yy',
onSelect: function(dateStr) {
    var d = $.datepicker.parseDate('dd/mm/yy', dateStr);
    var years = parseInt(1);

    d.setFullYear(d.getFullYear() + years);
    d.setDate(d.getDate()-1);
    $('#to').datepicker({dateFormat: 'dd/mm/yy',maxDate: d});
}
});

这是jsfiddle for jsfiddle