获取正确的每小时块

Get the correct hourly block

我需要以下用例的特定逻辑:

一天分为 6 部分 => 24 小时 / 6 小时 = 4 小时

所以我有 6 个街区,每个街区有 4 小时 => 00:00、04:00、08:00、12:00、16:00、20:00

我需要一个接受一天变量的函数(一个 Momentjs 对象)。

如果函数得到 11:30,则应返回或可见以下块 => 12:00、16:00、20:00、00:00

如果函数得到 23:00,则应返回或可见以下块 => 00:00、04:00、08:00、12:00

如果函数得到 06:00,则应返回或可见以下块 => 08:00、12:00、16:00、20:00

总是接下来的 4 小时块。

您可以取日期对象的小时部分,看看它被 4 除了多少次。用它来计算接下来的 4 个块。最后格式化成你想要的字符串:

let dt = moment(); // current date/time
let block = dt.hour() >> 2; // integer division by 4
// Add 1, 2, 3 and 4 to it, and map that to the starting hours of 
//   the next blocks (wrap around midnight using remainder operator)
let blocks = [1, 2, 3, 4].map(i => ((block + i) * 4) % 24);
// format the hours (numbers) as time strings in 00:00 format
console.log( blocks.map(hour => (hour+":00").padStart(5, "0")) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.0/moment.min.js"></script>

这应该有效。

function getNextBlocks(time){
    // gets hour from time
    var numTime = parseInt(time, 10);

    // rounds up to nearest 6
    var blocks = [Math.ceil(time / 6) * 6];

    // gets the next 3 blocks
    for(var i = 1; i < 4; i++){
        // gets value of previous block and adds 6
        var nextBlock = blocks[i-1] + 6;
    
        // if block is more than 23 it subtracts 24
        if(nextBlock >= 24){
            nextBlock -=24;
        }
    
        blocks.push(nextBlock);
    }

    // adds ":00" to the end of each block
    for(var i = 0; i < blocks.length; i++){
        blocks[i]+= ":00";
    }

    return blocks;
}

使用isSameOrAfter()

const blocks = ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00']

const hourlyBlock = (time) => {
  let mtime = moment(time, 'hh:mm')
  let index = blocks.findIndex(i => moment(i, 'hh:mm').isSameOrAfter(mtime))
  if (index == -1) index = blocks.length

  return blocks.slice(index, blocks.length).concat(blocks.slice(0, index)).slice(0, 4);
}

console.log(hourlyBlock('11:30').join())
console.log(hourlyBlock('23:00').join())
console.log(hourlyBlock('06:00').join())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js" integrity="sha256-ZsWP0vT+akWmvEMkNYgZrPHKU9Ke8nYBPC3dqONp1mY=" crossorigin="anonymous"></script>

这是您期望的吗?

您可以使用 add hours in moment 并将结果转换为您的需要

moment().add(4,'hours').format("HH")

在此之后您可以从该结果中获取时间并将其转换为您的需要 给出的是我从你的问题中理解的例子

 let now = moment()
 for(i=0;i<4;i++){
  console.log(now.format("HH") )
  now = now.add(4,'hours') // push this to array or any other datastructure as per your convenience
}