Search code examples
jquerydatepickertimepicker

How to set jquery.timepicker minTime dynamically based on datepicker selected date?


I doubt this is a duplicate as I have look everything I could find on SO to make sure of this but feel free to flag me if it is. I'm using jquery.datepicker and jquery.timepicker to let users select date and time of appointments. Appointments can only be set 2hours from current time if the date they select is today's date. If selected date is not today and in the future, than minTime is 6:00am. The code I use seems to only work once. What am I doing wrong?

//datepicker
var dateToday = new Date(); 
$( ".datepicker" ).datepicker({minDate: dateToday,dateFormat:'yy-mm-dd'});

//timepicker
//on date change compare dates to set time
$(document).on('change', '.datepicker', function() {
//
//get current time
var date_now = new Date();
/*
Append 'UTC' to the string before converting it to a date in javascript:
var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"

*/
var d = new Date(date_now + 'UTC');
var n = d.getTime();//miliseconds
//
//
//
//get appt date
//date format : yyyy-mm-dd
var thisyear = d.getFullYear();
var thismonth =(d.getMonth()+1);
var thisday = d.getDate();
//convert month
if (thismonth >= 1 && thismonth < 10){
var mm = '0'+thismonth;
}else{
var mm =thismonth;
}
//convert day
if (thisday >= 1 && thisday < 10){
var dd = '0'+thisday;
}else{
var dd =thisday;
}

//same date formats = true
var nowdate = thisyear + '-' + mm + '-' + dd;
var pickdate = $('.datepicker').val();

//compare dates
if(nowdate === pickdate){
//console.log('same dates');
//minimum booking time
//2 hours from now
//7200000 miliseconds
//add to current time
var minBook = n + 7200000;
//convert miliseconds to time
//minTime
var minTime = msToTime(parseInt(minBook)); 
}else{
//console.log('not same dates');
//set time
var minTime = '6:00am';
}

//timepicker
$('.timepicker').timepicker({
timeFormat: 'HH:mm',
interval: 30,
minTime: minTime,
maxTime: '9:00pm',
dynamic: false,
dropdown: true,
scrollbar: true
});
});
/**
* 
* 
* 
* 
* MILISEONDS TO HOUR
* 
* 
* 
*/
function msToTime(duration) {
var milliseconds = parseInt((duration % 1000) / 100),
seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;

return hours + ":" + minutes ;
}
<!--JQUERY UI CSS-->
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css">
<!--JQUERY-->
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<!--JQUERY UI JS-->
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
<!--TIMEP[PICKER JS]-->
<script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>
<!--TIMEPICKER CSS-->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css">


<!--datepicker-->
<input class="datepicker" type="text" placeholder="Date">

<!--timepicker-->
<input  class="timepicker" type="text" placeholder="Time">


Solution

  • Instead of initializing your timepicker on each change event you can move that code outside your event handler . Then , whenever your date gets changed you can use option to update your minTime value .

    Demo code :

    $(document).ready(function() {
      var dateToday = new Date();
      $(".datepicker").datepicker({
        minDate: dateToday,
        dateFormat: 'yy-mm-dd'
      });
      //intialize///
      $('.timepicker').timepicker({
        timeFormat: 'HH:mm',
        interval: 30,
        maxTime: '9:00pm',
        dynamic: false,
        dropdown: true,
        scrollbar: true
      });
      $(document).on('change', '.datepicker', function() {
        var date_now = new Date();
        var d = new Date(date_now + 'UTC');
        var n = d.getTime(); //miliseconds
        var thisyear = d.getFullYear();
        var thismonth = (d.getMonth() + 1);
        var thisday = d.getDate();
        //convert month
        if (thismonth >= 1 && thismonth < 10) {
          var mm = '0' + thismonth;
        } else {
          var mm = thismonth;
        }
        //convert day
        if (thisday >= 1 && thisday < 10) {
          var dd = '0' + thisday;
        } else {
          var dd = thisday;
        }
        var nowdate = thisyear + '-' + mm + '-' + dd;
        var pickdate = $('.datepicker').val();
        if (nowdate === pickdate) {
          var minBook = n + 7200000;
          var minTime = msToTime(parseInt(minBook));
        } else {
          var minTime = '6:00am';
        }
        $('.timepicker').timepicker('option', 'minTime', minTime); //update options...
      });
      $(".datepicker").trigger("change") //on load of page call this
    
      function msToTime(duration) {
        var milliseconds = parseInt((duration % 1000) / 100),
          seconds = Math.floor((duration / 1000) % 60),
          minutes = Math.floor((duration / (1000 * 60)) % 60),
          hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
    
        hours = (hours < 10) ? "0" + hours : hours;
        minutes = (minutes < 10) ? "0" + minutes : minutes;
        seconds = (seconds < 10) ? "0" + seconds : seconds;
    
        return hours + ":" + minutes;
      }
    })
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css">
    <input class="datepicker" type="text" placeholder="Date">
    <input class="timepicker" type="text" placeholder="Time">