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

如何判断当前UTC时间是否处于指定开闭时段?代码问题排查

解决跨天时段的市场状态判断问题

问题描述

现有代码用于判断当前时间是否处于指定开市时段并返回对应颜色,但处理跨天时段时结果错误:

  • 调用calculateMarketIndicator("22:00", "21:59")返回red(实际应为green,时段跨天覆盖次日)
  • 调用calculateMarketIndicator("23:01", "05:00")返回red(预期应为green)
  • 不跨天的时段(如"14:30", "21:00")能正常返回green

问题原因

原代码默认将开市的开始、结束时间都设置在同一天,当开始时间数值大于结束时间时(比如23:01 > 05:00),isBetween会判断当前时间是否在「当天23:01到当天05:00」这个无效区间内,自然返回false,导致错误返回red。

修复后的代码

const calculateMarketIndicator = (startTime, endTime) => {
  // 解析时分
  const [startHour, startMinute] = startTime.split(":").map(Number);
  const [endHour, endMinute] = endTime.split(":").map(Number);
  
  const currentDate = new Date();
  const currentUTC = moment(currentDate).utc();
  
  // 创建当天的开始时间UTC
  const startDate = new Date(currentDate);
  startDate.setHours(startHour, startMinute, 0, 0);
  const startUTC = moment(startDate).utc();
  
  // 创建当天的结束时间UTC
  const endDate = new Date(currentDate);
  endDate.setHours(endHour, endMinute, 0, 0);
  const endUTC = moment(endDate).utc();
  
  let isInMarket;
  if (startUTC.isAfter(endUTC)) {
    // 跨天情况:当前时间 >= 开始时间 或者 当前时间 <= 结束时间
    isInMarket = currentUTC.isAfter(startUTC) || currentUTC.isBefore(endUTC);
  } else {
    // 不跨天情况:当前时间在开始和结束之间
    isInMarket = currentUTC.isBetween(startUTC, endUTC);
  }
  
  return isInMarket ? COLORS.green : COLORS.red;
};

关键修改点

  • 增加跨天判断逻辑:先比较startUTC和endUTC的先后,如果startUTC在endUTC之后,说明是跨天时段,此时只要当前时间在「开始时间到当天结束」或者「次日0点到结束时间」范围内,就判定为开市(返回green)
  • 优化时分解析写法,用解构赋值更简洁
  • 移除冗余的变量重复声明(原代码重复声明了startTime和endTime)

内容的提问来源于stack exchange,提问作者Manish Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 19:27:16