Search code examples
javascriptjquerytimepicker

jquery-timepicker desable past time


Im using jquery time picker i wanted to disable the past time This is what I have currently

$('.timepicker').timepicker({ 
            'timeFormat': 'h:i A',
            'minTime' : "11:30 am",
            'maxTime' : "02:30 pm",
            'step': '30',
            'disableTimeRanges': [['10am', '11am']]
            
        });

im using https://github.com/jonthornton/jquery-timepicker


Solution

  • To make the minTime setting dynamic you can determine the current time using new Date(). From there you need to calculate the nearest 30 minute interval (as that's the step you're using). A reference to the function which calculates that date can then be provided to minDate. Try this:

    let roundDate = (date = new Date(), roundToMinutes = 30) => {
      const ms = 1000 * 60 * roundToMinutes;
      return new Date(Math.ceil(date.getTime() / ms) * ms);
    }
    
    $('.timepicker').timepicker({
      timeFormat: 'h:i A',
      minTime: roundDate,
      maxTime: "02:30 pm",
      step: '30',
      disableTimeRanges: [
        ['10am', '11am']
      ]
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-timepicker/1.13.18/jquery.timepicker.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-timepicker/1.13.18/jquery.timepicker.min.css" />
    <input type="text" class="timepicker" />