使用Bootstrap Datepicker选择月份日期范围和月份

时间:2017-09-09 09:35:52

标签: javascript jquery twitter-bootstrap date datepicker

如何使用Bootstrap Datepicker选择月份日期和月份的范围?

我目前正在使用jQuery UI datepicker来选择月份和周。

这是我尝试在月份转换的周日期范围的示例。但是问题

这里是js fiddle https://jsfiddle.net/prtk/znbx32j1/1/

的链接

HTML

<div class="form-group col-md-8 col-md-offset-2" id="week-picker-wrapper">
    <label for="week" class="control-label">Select Week</label>
    <div class="input-group">
        <span class="input-group-btn">
            <button type="button" class="btn btn-rm week-prev">&laquo;</button>
        </span>
        <input type="text" class="form-control week-picker" placeholder="Select a Week">
        <span class="input-group-btn">
            <button type="button" class="btn btn-rm week-next">&raquo;</button>
        </span>
    </div>
</div>

JS

var weekpicker, start_date, end_date;

function set_week_picker(date) {
    start_date = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
    end_date = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
    weekpicker.datepicker('update', start_date);
    weekpicker.val((start_date.getMonth() + 1) + '/' + start_date.getDate() + '/' + start_date.getFullYear() + ' - ' + (end_date.getMonth() + 1) + '/' + end_date.getDate() + '/' + end_date.getFullYear());
}
$(document).ready(function() {
    weekpicker = $('.week-picker');
    console.log(weekpicker);
    weekpicker.datepicker({
        autoclose: true,
        forceParse: false,
        container: '#week-picker-wrapper',
    }).on("changeDate", function(e) {
        set_week_picker(e.date);
    });
    $('.week-prev').on('click', function() {
        var prev = new Date(start_date.getTime());
        prev.setDate(prev.getDate() - 1);
        set_week_picker(prev);
    });
    $('.week-next').on('click', function() {
        var next = new Date(end_date.getTime());
        next.setDate(next.getDate() + 1);
        set_week_picker(next);
    });
    set_week_picker(new Date);
});

1 个答案:

答案 0 :(得分:1)

您需要修改prev事件的nextclick计算。检查this fiddle(检查控制台以查看值)。

使用setMonth()getMonth()代替setDate()getDate()。此外,您可能需要调整/设置日期值以获得准确的结果。

更新:这是updated fiddle