Search code examples
javascriptjquerydatetimepickertimepicker

How to write a condition block to check whether the selected time is in between of 5 hours of current time from the Timepicker


I need a solution to Timepicker. I added a time picker in Javascript and now user can select the time from the dropdown, but I want to check if the user selected the time in between of 5 hours of the current time, else return false. let me share you my code.

$('.timepicker').timepicker({
    timeFormat: 'h:mm p',
    setTime: new Date(),
    "minTime": "" + hour + ":" + minute + "",
    dynamic: true,
    dropdown: true,
    scrollbar: true,
    change: countneartime
});
function countneartime(){
    var d = new Date();
    var month = d.getMonth()+1;
    var day = d.getDate();
    var output = (month<10 ? '0' : '') + month + '/' +
    (day<10 ? '0' : '') + day + '/'+ d.getFullYear()  ;
    var pickup = $(".start-date").val();
    if(output == pickup){
        // write code to check condition if user selected time within 5 hours of upcoming

    }
}

I want to return false if user selected time is in the upcoming 5 hours of the current time. please help me


Solution

  • Try the following:

    let hour = 12,
      minute = 0;
    $('.timepicker').timepicker({
      timeFormat: 'h:mm p',
      "minTime": "" + hour + ":" + minute + "",
      dynamic: true,
      dropdown: true,
      scrollbar: true,
      change: countneartime
    });
    
    function countneartime(val) {
      var selected = new Date(val);
      var fiveHoursLater = new Date(0, 0, 0, new Date().getHours() + 5, new Date().getMinutes(), new Date().getSeconds());
      console.log(fiveHoursLater.getTime() > selected.getTime());
    }
    .as-console-wrapper {
      max-height: 40px !important;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css">
    <script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>
    
    <input class="timepicker" />