Javascript 如何限制 Bootstrap Datepicker 中的可选日期范围?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11933173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:44:54  来源:igfitidea点击:

How to restrict the selectable date ranges in Bootstrap Datepicker?

javascripttwitter-bootstrapdatepickerbootstrap-datepicker

提问by Alagappan Ramu

I need to use datepicker which provides me the option of restricting the selectable dates. We had been using jQuery UI which is used to support it using minDate, maxDate options.

我需要使用 datepicker,它为我提供了限制可选日期的选项。我们一直在使用 jQuery UI,它使用 minDate、maxDate 选项来支持它。

$("#id_date").datepicker({minDate: +1, maxDate: '+1M +10D'}); 

Recently we started using Twitter Bootstrap for our styles. And apparently, Twitter Bootstrap is incompatible with jQuery UI styles. So I tried using one of the bootstrap compatible datepickers available at http://www.eyecon.ro/bootstrap-datepicker/.

最近我们开始为我们的样式使用 Twitter Bootstrap。显然,Twitter Bootstrap 与 jQuery UI 样式不兼容。所以我尝试使用http://www.eyecon.ro/bootstrap-datepicker/ 上提供的与引导程序兼容的日期选择器之一。

Unfortunately, the above plugin is not as configurable as jQuery UI's datepicker. Can anyone help me out with restricting the selectable date ranges in the new datepicker.

不幸的是,上面的插件不像 jQuery UI 的日期选择器那样可配置。任何人都可以帮助我限制新日期选择器中的可选日期范围。

回答by Danny

The Bootstrap datepicker is able to set date-range. But it is not available in the initial release/Master Branch. Check the branch as 'range' there (or just see at https://github.com/eternicode/bootstrap-datepicker), you can do it simply with startDate and endDate.

Bootstrap 日期选择器能够设置日期范围。但它在初始版本/主分支中不可用。在那里检查分支为“范围”(或仅在https://github.com/eternicode/bootstrap-datepicker 上查看),您只需使用 startDate 和 endDate 即可。

Example:

例子:

$('#datepicker').datepicker({
    startDate: '-2m',
    endDate: '+2d'
});

回答by user2586273

With selectable date ranges you might want to use something like this. My solution prevents selecting #from_date bigger than #to_date and changes #to_date startDate every time when user selects new date in #from_date box:

对于可选择的日期范围,您可能想要使用这样的东西。我的解决方案防止选择大于 #to_date 的 #from_date 并在每次用户在 #from_date 框中选择新日期时更改 #to_date startDate:

http://bootply.com/74352

http://bootply.com/74352

JS file:

JS文件:

var startDate = new Date('01/01/2012');
var FromEndDate = new Date();
var ToEndDate = new Date();

ToEndDate.setDate(ToEndDate.getDate()+365);

$('.from_date').datepicker({

    weekStart: 1,
    startDate: '01/01/2012',
    endDate: FromEndDate, 
    autoclose: true
})
    .on('changeDate', function(selected){
        startDate = new Date(selected.date.valueOf());
        startDate.setDate(startDate.getDate(new Date(selected.date.valueOf())));
        $('.to_date').datepicker('setStartDate', startDate);
    }); 
$('.to_date')
    .datepicker({

        weekStart: 1,
        startDate: startDate,
        endDate: ToEndDate,
        autoclose: true
    })
    .on('changeDate', function(selected){
        FromEndDate = new Date(selected.date.valueOf());
        FromEndDate.setDate(FromEndDate.getDate(new Date(selected.date.valueOf())));
        $('.from_date').datepicker('setEndDate', FromEndDate);
    });

HTML:

HTML:

<input class="from_date" placeholder="Select start date" contenteditable="false" type="text">
<input class="to_date" placeholder="Select end date" contenteditable="false" type="text" 

And do not forget to include bootstrap datepicker.js and .css files aswell.

并且不要忘记包含 bootstrap datepicker.js 和 .css 文件。

回答by Marek

The example above can be simplify a bit. Additionally you can put date manually from keyboard instead of selecting it via datepicker only. When clearing the value you need to handle also 'on clearDate'action to remove startDate/endDate boundary:

上面的例子可以简化一点。此外,您可以从键盘手动输入日期,而不是仅通过日期选择器选择它。清除值时,您还需要处理'on clearDate'操作以删除 startDate/endDate 边界:

JS file:

JS文件:

$(".from_date").datepicker({
    format: 'yyyy-mm-dd',
    autoclose: true,
}).on('changeDate', function (selected) {
    var startDate = new Date(selected.date.valueOf());
    $('.to_date').datepicker('setStartDate', startDate);
}).on('clearDate', function (selected) {
    $('.to_date').datepicker('setStartDate', null);
});

$(".to_date").datepicker({
    format: 'yyyy-mm-dd',
    autoclose: true,
}).on('changeDate', function (selected) {
    var endDate = new Date(selected.date.valueOf());
    $('.from_date').datepicker('setEndDate', endDate);
}).on('clearDate', function (selected) {
    $('.from_date').datepicker('setEndDate', null);
});

HTML:

HTML:

<input class="from_date" placeholder="Select start date" type="text" name="from_date">
<input class="to_date" placeholder="Select end date" type="text" name="to_date">

回答by FavorMylikes

Most answers and explanations are not to explain what is a valid string of endDateor startDate. Danny gave us two useful example.

大多数答案和解释都不是为了解释什么是有效的endDateor字符串startDate。Danny 给了我们两个有用的例子。

$('#datepicker').datepicker({
    startDate: '-2m',
    endDate: '+2d'
});

But why?let's take a look at the source code at bootstrap-datetimepicker.js. There are some code begin line 1343 tell us how does it work.

但为什么呢?让我们看一下 的源代码bootstrap-datetimepicker.js。有一些代码开始行 1343 告诉我们它是如何工作的。

if (/^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$/.test(date)) {
            var part_re = /([-+]\d+)([dmwy])/,
                parts = date.match(/([-+]\d+)([dmwy])/g),
                part, dir;
            date = new Date();
            for (var i = 0; i < parts.length; i++) {
                part = part_re.exec(parts[i]);
                dir = parseInt(part[1]);
                switch (part[2]) {
                    case 'd':
                        date.setUTCDate(date.getUTCDate() + dir);
                        break;
                    case 'm':
                        date = Datetimepicker.prototype.moveMonth.call(Datetimepicker.prototype, date, dir);
                        break;
                    case 'w':
                        date.setUTCDate(date.getUTCDate() + dir * 7);
                        break;
                    case 'y':
                        date = Datetimepicker.prototype.moveYear.call(Datetimepicker.prototype, date, dir);
                        break;
                }
            }
            return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), 0);
        }

There are four kinds of expressions.

有四种表达方式。

  • wmeans week
  • mmeans month
  • ymeans year
  • dmeans day
  • w表示周
  • m表示月份
  • y意味着年
  • d意味着一天

Look at the regular expression ^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$. You can do more than these -0dor +1m.

看看正则表达式^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$。您可以做的不仅仅是这些-0d+1m

Try harder like startDate:'+1y,-2m,+0d,-1w'.And the separator ,could be one of [\f\n\r\t\v,]

更努力地像startDate:'+1y,-2m,+0d,-1w'.And 分隔符,可能是其中之一[\f\n\r\t\v,]

回答by overallduka

Another possibility is to use the options with dataattributes, like this(minimum date 1 week before):

另一种可能性是使用带有data属性的选项,如下所示(最少日期为 1 周前):

<input class='datepicker' data-date-start-date="-1w">

More info: http://bootstrap-datepicker.readthedocs.io/en/latest/options.html

更多信息:http: //bootstrap-datepicker.readthedocs.io/en/latest/options.html

回答by bresleveloper

i am using v3.1.3 and i had to use data('DateTimePicker')like this

我正在使用 v3.1.3,我不得不data('DateTimePicker')像这样使用

var fromE = $( "#" + fromInput );
var toE = $( "#" + toInput );
$('.form-datepicker').datetimepicker(dtOpts);

$('.form-datepicker').on('change', function(e){
   var isTo = $(this).attr('name') === 'to';

   $( "#" + ( isTo ? fromInput : toInput  ) )
      .data('DateTimePicker')[ isTo ? 'setMaxDate' : 'setMinDate' ](moment($(this).val(), 'DD/MM/YYYY'))
});