3

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

It can never round down just always up to the next time.

I am using this code at the moment but this will round down as well

var time = 1000 * 60 * 5;
var date = new Date();
var rounded = new Date(Math.round(date.getTime() / time) * time);
Community
  • 1
  • 1
Eli Stone
  • 1,515
  • 4
  • 33
  • 57

6 Answers6

10

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
EagleV_Attnam
  • 737
  • 6
  • 11
  • What happens if it's 11:58 or 11:59? The result should also be 12:00 in these cases.. wouldn't your solution bump this incorrectly to 12:05? – Drewdavid Sep 14 '18 at 17:36
  • @Drewdavid No, because 11:58 + 2.5 = 12:00:30 -> rounded to 12:00. This is the same idea as https://stackoverflow.com/a/9001654/1194019 – pba Sep 24 '18 at 09:00
  • Ah, makes sense now thanks... I was stuck on thinking about rounding up only. – Drewdavid Sep 24 '18 at 22:31
10

You could divide out 5, do a Math.ceil then multiply back up by 5

minutes = (5 * Math.ceil(minutes / 5));
Paul S.
  • 64,864
  • 9
  • 122
  • 138
2

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));
Rafael Lebre
  • 576
  • 1
  • 8
  • 16
2

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
1
var b = Date.now() + 15E4,
    c = b % 3E5;
    rounded = new Date(15E4>=c?b-c:b+3E5-c);
Endless
  • 34,080
  • 13
  • 108
  • 131
1

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
peter.bartos
  • 11,855
  • 3
  • 51
  • 62