Search code examples
javascriptjquerytwitter-bootstrapbootstrap-datetimepicker

Bootstrap datetimepicker disable future date and time


I am trying to disable future hours within today using disabledTimeIntervals but it doesn't seem to work.

What I need to do is disable future hours in timepicker for today only, because disabling dates I can do with maxDate.

<input class="form-control input-sm pull-left " id="dp" placeholder="To" type="text">
$('#dp').datetimepicker({
  maxDate: '0',
  disabledTimeIntervals: [[moment(), moment().hour(24).minutes(0).seconds(0)]],
  format: 'm/d/Y H:i A',
  timepicker: true,
});

JSFIDDLE: https://jsfiddle.net/3oxmccjq/1/


Solution

  • You can use maxTime option and function onChangeDateTime to set the minTime according to the selected date.

    • The comparison between dates is up to you :-)

    var today = new Date();
    
    var options = {
      maxDate: new Date(),
      maxTime: new Date(),
      disabledTimeIntervals: [
        [moment(), moment().hour(24).minutes(0).seconds(0)]
      ],
      format: 'm/d/Y H:i A',
      timepicker: true,
      onChangeDateTime: function(date) {
        // Here you need to compare date! this is up to you :-)
        if (date.getDate() === today.getDate()) {
          this.setOptions({maxTime: new Date()});
        } else {
          this.setOptions({maxTime: false});
        }
      }
    };
    
    $('#dp').datetimepicker(options);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.4/build/jquery.datetimepicker.full.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.4/jquery.datetimepicker.css" rel="stylesheet" />
    
    <input class="form-control input-sm pull-left " id="dp" placeholder="To" type="text">