Success Man Success Man - 1 month ago 14
jQuery Question

How can I add a minimum of days based on hour in datetimepicker?

My code javascript like this :

$(function () {
$('#datepicker').datetimepicker({
minDate: moment().startOf('day')
}).on('dp.change', function(e){
if( e.date && e.date.isSame(moment(), 'd') ){
var min = moment().startOf('minute').add(300, 'm');
$('#timepicker').data("DateTimePicker").minDate(min);
} else {
$('#timepicker').data("DateTimePicker").minDate(false);
}
});

$('#timepicker').datetimepicker({
minDate: moment().startOf('minute').add(300, 'm'),
});
});


Demo and full code like this : https://jsfiddle.net/tyvetr5h/

My problem :

For example now on 16 August at 9 pm. As it appears that the date displayed is 17 August at 2 am. But my code is August 16 at 2 am

How can I solve it?

I try to update the day like this :

minDate: moment().startOf('day').add(300, 'm')


But it's the same

Answer Source

You have to add the 300 minutes to the DP mindate when instantiating too. Since this "moment" is the current time and date, that is relevant to add it.

I'm not the same timezone as you, so I had to add more than 300 minutes to make it fall on tomorrow... But here is your updated Fiddle. I removed all .startOf(), which I think is irrelevant in what you try to achieve.

EDIT
I found the trick.

The thing is that you change the moment value... so when it is time to compare the dates, better do it in "Unix format", which is in milliseconds from january 1st 1970...

That long integer doesn't care about the day change. So it is easier (and error proof) to compare if the time is 300 minutes from now.

$(function () {

  console.clear();

  $('#datepicker').datetimepicker({
    minDate: moment().add(300, 'm').startOf("day")
  })
    .val(moment().add(300, 'm').format("DD-MM-YYYY"))   // To set correct "valid" date from start

    .on('dp.change', function(e){
    var now = moment().format("X");
    //console.log(e.date.format("X"));
    //console.log(now);

    // Comparing selected date (moment object) in milliseconds
    if(e.date.format("X")+(300*60*1000) > now ){
      console.log("above 5 hours, unlocking time.");
      $('#timepicker').data("DateTimePicker").minDate(false);
    }else{
      console.log("below 5 hours, locking time (and probably resetting the value to min...)");
      $('#timepicker').data("DateTimePicker").minDate(moment().add(300, 'm'));
    }

  });

  $('#timepicker').datetimepicker({
    minDate: moment().add(300, 'm'),
  });
});

CodePen