You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术需求:计算转子24小时内各循环启动时间(间隔80分钟)

问题与解决方案

需求描述

在一个小型项目里,需要计算转子24小时内的所有后续启动时间。转子的运行规律是工作40分钟,接着待机40分钟,初始启动时间是11:40,最终要输出所有符合要求的后续启动时间(比如13:00、14:20这类)。

现有代码问题

你提供的代码存在几个明显问题:

  • JavaScript里没有time这个内置构造函数,正确的时间处理应该用Date对象;
  • 代码只做了一次40分钟的时间偏移,没有循环生成24小时内的所有启动时间,完全达不到需求要求。

现有代码片段:

const time = new time('11:40');

time.setMinutes(time.getMinutes() + 40);


console.log(time); 

正确实现代码

下面是能满足需求的完整代码:

// 初始化初始启动时间为当天的11:40
const initialStartTime = new Date();
initialStartTime.setHours(11, 40, 0, 0);

// 转子的完整周期:工作40分钟 + 待机40分钟 = 80分钟
const cycleDuration = 80;
const allStartTimes = [];

// 定义24小时后的截止时间
const endTime = new Date(initialStartTime);
endTime.setHours(endTime.getHours() + 24);

// 从第一次后续启动时间开始计算
let currentTime = new Date(initialStartTime);
currentTime.setMinutes(currentTime.getMinutes() + cycleDuration);

// 循环生成所有在24小时内的启动时间
while (currentTime < endTime) {
    // 格式化为HH:mm的字符串格式
    const hours = currentTime.getHours().toString().padStart(2, '0');
    const minutes = currentTime.getMinutes().toString().padStart(2, '0');
    allStartTimes.push(`${hours}:${minutes}`);
    
    // 累加一个周期的时间
    currentTime.setMinutes(currentTime.getMinutes() + cycleDuration);
}

console.log('24小时内的后续启动时间:', allStartTimes);

代码说明

  • 用Date对象准确初始化初始时间,避免直接传字符串的兼容性问题;
  • 以80分钟为一个完整周期(工作+待机),每次循环累加一个周期的时间;
  • 循环终止条件是当前时间超过初始时间24小时后,确保只计算一天内的启动时间;
  • 把每个时间格式化为两位数的小时和分钟,保证输出格式统一(比如00:20而不是0:20)。

内容的提问来源于stack exchange,提问作者Pascal B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 17:00:11