bootstrap-daterangepicker

Limit daterange calender to one year ahead?


I've inherited a website and although the daterangepicker on the site is working perfectly - the client now needs the date range limited to one year ahead from today's date.

How do I edit the existing code to include this functionality?

      $(function () {
    var today = new Date();
    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);

    arriving = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
    departing = tomorrow.getFullYear() + '-' + (tomorrow.getMonth() + 1) + '-' + tomorrow.getDate();

    $('input#datepicker').daterangepicker({
        autoApply: true,
        startDate: today, // preselect dates
        endDate: tomorrow, locale: {
            format: "DD MMM YYYY"
        },
        minDate: today
    }, function (start, end, label) {
        if (start.isSame(end, 'day')) {
            end.add(1, 'days');
            $('#datepicker').data('daterangepicker').setEndDate(end);
        }
        arriving = start.format('YYYY-MM-DD');
        departing = end.format('YYYY-MM-DD');

    });

});


Solution

  • Welcome to stackoverflow. You can set maxDate to one year from today. You could try the following

    $(function () {
            var today = new Date();
            var tomorrow = new Date();
            tomorrow.setDate(tomorrow.getDate() + 1);
    
            arriving = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
            departing = tomorrow.getFullYear() + '-' + (tomorrow.getMonth() + 1) + '-' + tomorrow.getDate();
    
            $('input#datepicker').daterangepicker({
                autoApply: true,
                startDate: today, // preselect dates
                endDate: tomorrow, locale: {
                    format: "DD MMM YYYY"
                },
                minDate: today,
                maxDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1))
            }, function (start, end, label) {
                if (start.isSame(end, 'day')) {
                    end.add(1, 'days');
                    $('#datepicker').data('daterangepicker').setEndDate(end);
                }
                arriving = start.format('YYYY-MM-DD');
                departing = end.format('YYYY-MM-DD');
    
            });