Eli Stone
Eli Stone

Reputation: 1555

Javascript: Round Time UP nearest 5 minutes

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

Upvotes: 3

Views: 7780

Answers (6)

Shubham Rai
Shubham Rai

Reputation: 39

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

Upvotes: 2

peter.bartos
peter.bartos

Reputation: 12045

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

Upvotes: 1

Rafael Lebre
Rafael Lebre

Reputation: 586

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

Upvotes: 2

Endless
Endless

Reputation: 37885

var b = Date.now() + 15E4,
    c = b % 3E5;
    rounded = new Date(15E4>=c?b-c:b+3E5-c);

Upvotes: 1

Paul S.
Paul S.

Reputation: 66364

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

minutes = (5 * Math.ceil(minutes / 5));

Upvotes: 10

EagleV_Attnam
EagleV_Attnam

Reputation: 747

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

Upvotes: 10

Related Questions