Javascript: Round Time UP最接近5分钟

Javascript: Round Time UP nearest 5 minutes

本文关键字:最接近 5分钟 UP Time Round Javascript      更新时间:2023-09-26

我需要把时间调到最近的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);

给你的时间加上2.5分钟,然后四舍五入

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

你可以把5除以Math.ceil再乘以5

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

我有同样的问题,但我需要四舍五入,我把你的代码改成这样:

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

以毫秒为单位传递任何周期以获得下一个周期示例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

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

使用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