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

求助:基于Google Calendar API的JS可用时段计算代码修复

修正可用时段计算代码以匹配预期输出

已有通过Google Calendar API获取的已预订事件列表,需要计算间隔15分钟、会议时长60分钟的可用时段,预期输出为['8:00', '10:00', '12:30', ..., '15:00']格式的时段起始时间字符串。原代码输出不符合预期,以下是修正方案。

原代码核心问题

  1. 时区不统一:事件时间是UTC时区(带+0000),而工作时间未指定时区,导致时间对比出现偏差。
  2. 冲突判断逻辑错误:原条件重复判断且逻辑颠倒,未正确识别时段与事件的重叠情况。
  3. 输出格式不符:使用toUTCString()生成的格式不符合预期的HH:mm格式。
  4. 循环边界错误:未考虑会议结束时间不能超过工作结束时间,可能生成无效时段。

修正后的代码

const events = [
  { startTime: new Date('2023-10-18T00:00:00+0000'), endTime: new Date('2023-10-18T08:00:00+0000') },
  { startTime: new Date('2023-10-18T09:00:00+0000'), endTime: new Date('2023-10-18T10:00:00+0000') },
  { startTime: new Date('2023-10-18T11:00:00+0000'), endTime: new Date('2023-10-18T12:30:00+0000') },
  { startTime: new Date('2023-10-18T16:00:00+0000'), endTime: new Date('2023-10-18T17:30:00+0000') },
  { startTime: new Date('2023-10-18T18:00:00+0000'), endTime: new Date('2023-10-19T00:00:00+0000') },
];

const meetingDuration = 60; // 分钟
const interval = 15; // 分钟
// 统一使用UTC时区定义工作时间,避免时区偏差
const workdayStart = new Date('2023-10-18T08:00:00+0000'); 
const workdayEnd = new Date('2023-10-18T17:00:00+0000');

const availableSlots = [];

let currentSlotStart = new Date(workdayStart);

// 循环条件:确保会议结束时间不超过工作结束时间
while (currentSlotStart.getTime() + meetingDuration * 60 * 1000 <= workdayEnd.getTime()) {
  const currentSlotEnd = new Date(currentSlotStart);
  currentSlotEnd.setMinutes(currentSlotEnd.getMinutes() + meetingDuration);

  // 判断当前时段与所有事件都不重叠
  const isAvailable = events.every(event => {
    // 不重叠的两种情况:当前时段完全在事件之前,或完全在事件之后
    return currentSlotEnd <= event.startTime || currentSlotStart >= event.endTime;
  });

  if (isAvailable) {
    // 格式化为HH:mm格式的UTC时间字符串
    const hours = currentSlotStart.getUTCHours();
    const minutes = currentSlotStart.getUTCMinutes();
    availableSlots.push(`${hours}:${minutes.toString().padStart(2, '0')}`);
  }

  currentSlotStart.setMinutes(currentSlotStart.getMinutes() + interval);
}

console.log(availableSlots);
// 输出:['8:00', '10:00', '12:30', '12:45', '13:00', '13:15', '13:30', '13:45', '14:00', '14:15', '14:30', '14:45', '15:00']

关键修正说明

  1. 统一时区:将工作时间改为UTC时区(添加+0000),与事件时间保持一致,避免时区转换导致的时间偏差。
  2. 修正冲突判断:使用currentSlotEnd <= event.startTime || currentSlotStart >= event.endTime准确判断时段与事件无重叠。
  3. 调整循环边界:通过时间戳计算确保会议结束时间不超过工作结束时间,过滤无效时段。
  4. 格式化输出:使用UTC时间方法提取时分,格式化为符合预期的HH:mm字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 03:24:56