Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Expected Result

Round Off Time : 15 min

Given Time 10:00 => Rounded to: 10:00

Given Time 10:13 => Rounded to: 10:15

Given Time 10:15 => Rounded to: 10:15

Given Time 10:16 => Rounded to: 10:30

Given Time 16:00 => Rounded to: 16:00

Given Time 16:12 => Rounded to: 16:15

Round Off Time varies based on user input

MyCode

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

Current Output

Given time: 08:22 => Rounded to: 08:15

Given time: 08:23 => Rounded to: 08:30

Need round off time should be in increment order

like image 408
siva Avatar asked Sep 07 '17 05:09

siva


People also ask

How do you round off time in a moment?

To round up, you need to add a minute and then round it down. To round down, just use the startOf method. Note the use of a ternary operator to check if the time should be rounded (for instance, 13:00:00 on the dot doesn't need to be rounded).

What is _D and _I in moment?

_i can also be undefined, in the case of creating the current moment with moment() . _d is the instance of the Date object that backs the moment object. If you are in "local mode", then _d will have the same local date and time as the moment object exhibits with the public API.


2 Answers

You could take all minutes and divide by 15 for getting the whole quarter and multiply by 15 for the result. Then take hours and minutes and apply formatting. Return joined values.

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));
like image 98
Nina Scholz Avatar answered Sep 28 '22 17:09

Nina Scholz


Try 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);
like image 21
Pritam Banerjee Avatar answered Sep 28 '22 19:09

Pritam Banerjee