datetimepicker - 使用四舍五入到最接近的 5 分钟的时间

问题描述 投票:0回答:1

我正在使用引导程序日期时间选择器。我想让时间四舍五入到最接近的 5 分钟。

我试过:

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'
        })
    }
);

在控制台中,我看到创建了舍入日期对象。然而,在日期时间选择器中,不使用四舍五入的日期,而是使用当前日期。

我做错了什么?

javascript datetimepicker
1个回答
1
投票

我的版本:

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
  });
});

更新:

$(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);
  });
});

© www.soinside.com 2019 - 2024. All rights reserved.