[removed] Round Time UP nearest 5 minutes

前端 未结 6 1262
悲&欢浪女
悲&欢浪女 2021-01-06 21:59

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

<
6条回答
  •  忘掉有多难
    2021-01-06 22:34

    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

提交回复
热议问题