[removed] Round Time UP nearest 5 minutes

前端 未结 6 1214
悲&欢浪女
悲&欢浪女 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:17

    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));
    
    0 讨论(0)
  • 2021-01-06 22:22

    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
    
    0 讨论(0)
  • 2021-01-06 22:31
    var b = Date.now() + 15E4,
        c = b % 3E5;
        rounded = new Date(15E4>=c?b-c:b+3E5-c);
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-06 22:41

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

    minutes = (5 * Math.ceil(minutes / 5));
    
    0 讨论(0)
  • 2021-01-06 22:43

    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
    
    0 讨论(0)
提交回复
热议问题