javascriptjquerydatetimepicker

Disable specific times on a specific date using jQuery DateTimePicker


I am trying to disable specific times for specific dates using the jQuery DateTimePicker like this:

jQuery('#datetimepicker').datetimepicker({
    disabledDates: ['27/04/2022 14:00'],
    format:'d/m/Y H:i'
});

However, this does not work. I can either only disable specific times for every day, or disable specific dates.


Solution

  • Ok I actually managed to figure this out myself. I'm using PHP, but you can essentially just use any multidimensional array and JSON encode it.

    $times[]=[
        '2022-04-28'=>[
            'hour' => 10,
            'minute' => 30
        ]
    ];
    $times[]=[
        '2022-04-28'=>[
            'hour' => 11,
            'minute' => 15
        ]
    ];
    $times[]=[
        '2022-04-29'=>[
            'hour' => 13,
            'minute' => 30
        ]
    ];
    
    $dates=json_encode($times);
    

    Once you have your list of dates and times you can use the onGenerate() function to loop through your dates and add a disabled class to the specific times.

    jQuery('#datetimepicker').datetimepicker({
        lang:'en',
        format:'Y-m-d H:i',
        formatDate:'Y-m-d',
        step:15,
        onGenerate: function(ct, $i){
            var date=moment(ct).format('Y-MM-D');
            var datesArray=<?echo $dates;?>;
    
            $.each(datesArray, function(i, dates){
                if(date in dates){
                    var times=dates[date];
                    $.each(times, function(index, time){
                        var hour=times['hour'];
                        var minute=times['minute'];
                        var $object=$('[data-hour="' + hour + '"][data-minute="' + minute + '"]');
                        $object.addClass('xdsoft_disabled');
                    });
                }
            });
        }
    });
    

    Please note: you will need to use the exact same date format for your array and jQuery function. Also, my step is set to 15 minute increments. So this only disables that exact step.