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

如何阻止重叠时间范围的对象存入已有时间记录的数组?

解决时间范围重叠校验的实现方案

没问题,我来帮你搞定这个禁止添加重叠时间记录的需求!核心思路就是在添加新记录前,先和数组里已有的每条记录做时间重叠判断,只要有一条重叠就拒绝添加,否则就存入数组。下面是具体的实现步骤和代码:

步骤1:字符串日期转Date对象

首先要把你数组里的StrngStartDate和StrngEndDate字符串转换成JavaScript的Date对象,这样才能准确比较时间先后。注意你的日期字符串里带有多余的双引号,需要先去掉:

function parseDate(dateStr) {
  // 移除字符串中的双引号,再转换为Date对象
  return new Date(dateStr.replace(/"/g, ''));
}

步骤2:编写时间重叠判断函数

这是核心逻辑,我们需要判断两个时间范围是否存在重叠。这里用一个通用的判断条件:新记录的开始时间 < 已有记录的结束时间,且新记录的结束时间 > 已有记录的开始时间,这个条件能覆盖所有重叠场景(比如包含、部分重叠等):

function isTimeOverlap(newItem, existingItem) {
  const newStart = parseDate(newItem.StrngStartDate);
  const newEnd = parseDate(newItem.StrngEndDate);
  const existingStart = parseDate(existingItem.StrngStartDate);
  const existingEnd = parseDate(existingItem.StrngEndDate);

  // 核心重叠判断逻辑,覆盖所有重叠情况
  return newStart < existingEnd && newEnd > existingStart;
}

步骤3:实现添加校验逻辑

最后写一个添加函数,遍历数组检查是否有重叠记录,根据结果决定是否添加:

function addTimeRecord(recordsArray, newRecord) {
  // 检查数组中是否存在与新记录重叠的条目
  const hasOverlap = recordsArray.some(record => isTimeOverlap(newRecord, record));

  if (hasOverlap) {
    console.log("⚠️ 该时间范围与已有记录重叠,无法添加!");
    return false; // 返回false表示添加失败
  } else {
    recordsArray.push(newRecord);
    console.log("✅ 记录添加成功!");
    return true; // 返回true表示添加成功
  }
}

示例使用

用你提供的初始数组来测试一下:

// 你的初始时间记录数组
const timeRecords = [
  {StrngStartDate: "\"09/19/2020 06:00:00\"", StrngEndDate: "\"09/19/2020 07:00:00\"", GoalId: 16352, CreatedBy: NaN, ReasonForAdding: "tre"},
  {StrngStartDate: "\"09/19/2020 06:00:00\"", StrngEndDate: "\"09/19/2020 06:30:00\"", GoalId: 16352, CreatedBy: NaN, ReasonForAdding: "rrre"}
];

// 尝试添加一条重叠的记录(6:30-7:30,和第一条6:00-7:00重叠)
const overlapRecord = {StrngStartDate: "\"09/19/2020 06:30:00\"", StrngEndDate: "\"09/19/2020 07:30:00\"", GoalId: 16352, CreatedBy: NaN, ReasonForAdding: "test overlap"};
addTimeRecord(timeRecords, overlapRecord); // 输出:⚠️ 该时间范围与已有记录重叠,无法添加!

// 尝试添加一条不重叠的记录(7:00-8:00)
const nonOverlapRecord = {StrngStartDate: "\"09/19/2020 07:00:00\"", StrngEndDate: "\"09/19/2020 08:00:00\"", GoalId: 16352, CreatedBy: NaN, ReasonForAdding: "test non-overlap"};
addTimeRecord(timeRecords, nonOverlapRecord); // 输出:✅ 记录添加成功!

这样就能完美实现你要的需求啦,不管是完全包含、部分重叠的情况都能准确拦截~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 11:57:35