How to round to the nearest hour and minutes by incrementing in JavaScript without using moment.js?

Expected Result

Rounding time : 15 minutes

This time is 10:00 => Rounded until: 10:00

This time is 10:13 => Rounded up: 10:15

This time is 10:15 => Rounded up: 10:15

This time is 10:16 => Rounded up: 10:30

This time is 4:00 p.m. => Rounded up to: 4:00 p.m.

This time is 16:12 => Rounded up: 16:15

Rounding time depends on user input

Mycode

var m = (((minutes + 7.5)/roundOffTime | 0) * roundOffTime) % 60;
var h = ((((minutes/105) + .5) | 0) + hours) % 24;

Current output

This time: 08:22 => Rounded up: 08:15

This time: 08:23 => Rounded until: 08:30

The required rounding time should be in increasing order

+4
source share
2

15 15 . . .

function roundMinutes(t) {
    function format(v) { return v < 10 ? '0' + v: v; }

    var m = t.split(':').reduce(function (h, m) { return h * 60 + +m; });
    
    m = Math.ceil(m / 15) * 15;
    return [Math.floor(m / 60), m % 60].map(format).join(':');
}

var data = ['10:00', '10:13', '10:15', '10:16', '16:00', '16:12', '16:55'];

console.log(data.map(roundMinutes));
+5

this:

var coeff = 1000 * 60 * 5;
var date = new Date();  //or use any other date
console.log(date);
var rounded = new Date(Math.round(date.getTime() / coeff) * coeff);
console.log(rounded);
+1

Source: https://habr.com/ru/post/1685208/


All Articles