I need to be able to round time to the next nearest 5 minutes.
<Time now 11:54 - clock is 11:55
Time now 11:56 - clock is 12:00
I had the same problem, but I needed to round down, and I changed your code to this:
var time = 1000 * 60 * 5;
var date = new Date();
var rounded = new Date(date.getTime() - (date.getTime() % time));
I think that to round up It wiil be something like this:
var time = 1000 * 60 * 5;
var date = new Date();
var rounded = new Date(date.getTime() + time - (date.getTime() % time));
Add 2.5 minutes to your time, then round.
11:54 + 2.5 = 11:56:30 -> 11:55
11:56 + 2.5 = 11:58:30 -> 12:00
var b = Date.now() + 15E4,
c = b % 3E5;
rounded = new Date(15E4>=c?b-c:b+3E5-c);
Pass any cycle you want in milliseconds to get next cycle example 5,10,15,30,60 minutes
function calculateNextCycle(interval) {
const timeStampCurrentOrOldDate = Date.now();
const timeStampStartOfDay = new Date().setHours(0, 0, 0, 0);
const timeDiff = timeStampCurrentOrOldDate - timeStampStartOfDay;
const mod = Math.ceil(timeDiff / interval);
return new Date(timeStampStartOfDay + (mod * interval));
}
console.log(calculateNextCycle(5 * 60 * 1000)); // pass in milliseconds
You could divide out 5
, do a Math.ceil
then multiply back up by 5
minutes = (5 * Math.ceil(minutes / 5));
With ES6 and partial functions it can be elegant:
const roundDownTo = roundTo => x => Math.floor(x / roundTo) * roundTo;
const roundUpTo = roundTo => x => Math.ceil(x / roundTo) * roundTo;
const roundUpTo5Minutes = roundUpTo(1000 * 60 * 5);
const ms = roundUpTo5Minutes(new Date())
console.log(new Date(ms)); // Wed Jun 05 2019 15:55:00 GMT+0200