Javascript:Round Time UP最接近5分钟

时间:2014-03-27 12:03:22

标签: javascript date

我需要能够将时间缩短到接近5分钟。

  

现在时间11:54 - 时钟是11:55

     

现在时间11:56 - 时钟是12:00

永远不会向下舍入到下一次。

我现在正在使用此代码,但这也将向下舍入

var time = 1000 * 60 * 5;
var date = new Date();
var rounded = new Date(Math.round(date.getTime() / time) * time);

6 个答案:

答案 0 :(得分:8)

加上2.5分钟到你的时间,然后回合。

11:54 + 2.5 = 11:56:30 -> 11:55
11:56 + 2.5 = 11:58:30 -> 12:00

答案 1 :(得分:6)

您可以将5分开,然后Math.ceil然后再乘以5

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

答案 2 :(得分:1)

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

答案 3 :(得分:1)

我遇到了同样的问题,但我需要向下舍入,我将代码更改为:

var time = 1000 * 60 * 5;
var date = new Date();
var rounded = new Date(date.getTime() - (date.getTime() % time));

我认为要整理它会是这样的:

var time = 1000 * 60 * 5;
var date = new Date();
var rounded = new Date(date.getTime() + time - (date.getTime() % time));

答案 4 :(得分:1)

以毫秒为单位传递任何您想要的周期,以获取下一个周期示例5,10,15,30,60分钟

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

答案 5 :(得分:0)

借助ES6和部分功能,它可能很优雅:

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