Search code examples
jquerydaterangepicker

How to limit hour in Date Range Picker JQuery Plugin


I am using Date Range Picker JQuery plugin and i can't limit the hour. I want to user can select 8 AM to 5 PM.

My Code:

$('input[name="date"]').daterangepicker({
    singleDatePicker: true,
    showDropdowns: true,
    timePicker: true,
    timePicker24Hour: true,
    timePickerIncrement: 30,
    "locale": {
        "format": "YYYY-MM-DD hh:mm",
        "applyLabel": "Onayla",
        "cancelLabel": "İptal",
        "weekLabel": "H",
        "daysOfWeek": [
            "Pa",
            "Pt",
            "Sa",
            "Ça",
            "Pe",
            "Cu",
            "Ct"
        ],
        "monthNames": [
            "Ocak",
            "Şubat",
            "Mart",
            "Nisan",
            "Mayıs",
            "Haziran",
            "Temmuz",
            "Ağustos",
            "Eylül",
            "Ekim",
            "Kasım",
            "Aralık"
        ],
        "firstDay": 1
    },
    minDate: moment().startOf('day').add(1,'day'),
    maxDate: moment().startOf('month').add(6,'month'),
    startDate: moment().startOf('day').add(1,'day'),
    MinTime: moment().hour(0).add(8)
});

I solve this problem with this code:

$('input[name="date"]').on('apply.daterangepicker', function(ev, picker) {
    if(picker.startDate.hour() > 17 || picker.startDate.hour() < 8){
        $('input[name="date"]').data('daterangepicker').setStartDate(picker.startDate.hour(0).add(8,'hour'));
        //ev.preventDefault();
    }
});

But i don't want to show them 0 to 24 hours. Just 8 to 17.

Edit: I used that code but didn't change anything.

hourMin: 8,
hourMax: 16,

Solution

  • It seems that the library does not allow natively what you want to achieve. It would be nice to have minHour and maxHour (as you suggest).

    What you can do to trick the user is to hide with CSS the hours you do not want him to choose:

    // This will hide the first 8 items so that 8 hours is the first option shown.
    .hourselect option:nth-child(-n+8) {
        display: none;
    }
    // This will hide the hours from 18 onwards.
    .hourselect option:nth-child(n+19) {
        display: none;
    }
    

    With this you are hiding the unwanted hours. The problem is the first time you open the range picker you see 0 as the selected hour. To correct this you can set your startDate so that it starts from 8:

    startDate: moment().startOf('day').add(1,'day').add(8, 'hours'),
    

    Another solution based on JavaScript is to remove the undesired hours when the user opens the range picker:

    $('input[name="daterange"]').on('show.daterangepicker', function(ev, picker) {
        var $hours = picker.container.find('.hourselect').children();
    
        $hours.filter(':gt(17)').remove();    
        $hours.filter(':lt(8)').remove();
    });