Search code examples
javascriptdatetimepicker

datetimepicker - use a time that is rounded to nearest 5 minutes


I am using a bootstrap datetimepicker. I want to have the time rounded up to the nearest 5 minutes.

I tried:

var coeff = 1000 * 60 * 5;
var date = new Date(); //or use any other date
var rounded = new Date(Math.round(date.getTime() / coeff) * coeff);
console.log('rounded = ' + rounded)
$(document).ready(
    function() {
        $('#meetingTime').datetimepicker({
            defaultDate: rounded,
            format: 'HH:mm'
        });
        $('#meetingTime').datetimepicker({
            defaultDate: rounded,
            format: 'HH:mm'
        })
    }
);

In the console I see that rounded up date object is created. However in the datetimepicker the rounded up date is not used and the current date is used.

What am I doing wrong?


Solution

  • My version:

    var coeff = 1000 * 60 * 5;
    var date = new Date(); //or use any other date
    var rounded = new Date(Math.round(date.getTime() / coeff) * coeff);
    console.log('rounded = ' + rounded);
    
    $(document).ready(function() {
      $('#meetingTime').datetimepicker({
        date: rounded,
        format: 'HH:mm',
        stepping: 5 // optional: sets the increment of the minutes to 5
      });
    });

    Update:

    $(document).ready(function() {
      $('#meetingTime').datetimepicker({
        format: 'HH:mm',
        stepping: 5 // optional: sets the increment of the minutes to 5
      }).on('focusin', function() {
        var coeff = 1000 * 60 * 5;
        var date = new Date(); //or use any other date
        var rounded = new Date(Math.round(date.getTime() / coeff) * coeff);
        $(this).data('DateTimePicker').date(rounded);
      });
    });