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

请求编写判断到达是否接近的函数:接收参数确定时间间隔

判断到达时间是否接近的函数实现

核心逻辑是计算两个到达时间的绝对差值,与设定的时间间隔阈值对比,若差值小于等于阈值则返回true,否则返回false。以下是主流编程语言的实现示例:

Python 实现

基于时间戳(整数,单位统一即可,如秒/毫秒)

def is_arrival_close(time1, time2, threshold):
    time_diff = abs(time1 - time2)
    return time_diff <= threshold

基于datetime对象

from datetime import datetime, timedelta

def is_arrival_close(time1: datetime, time2: datetime, threshold: timedelta) -> bool:
    return abs(time1 - time2) <= threshold

使用示例:

# 允许的最大间隔为5分钟
threshold = timedelta(minutes=5)
time_a = datetime(2024, 5, 20, 14, 30)
time_b = datetime(2024, 5, 20, 14, 33)
print(is_arrival_close(time_a, time_b, threshold))  # 输出True

JavaScript 实现

基于时间戳(毫秒级整数)

function isArrivalClose(time1, time2, threshold) {
    const timeDiff = Math.abs(time1 - time2);
    return timeDiff <= threshold;
}

基于Date对象

function isArrivalClose(time1, time2, threshold) {
    // threshold传入毫秒数,比如5分钟就是5*60*1000=300000
    const timeDiff = Math.abs(time1.getTime() - time2.getTime());
    return timeDiff <= threshold;
}

使用示例:

const threshold = 5 * 60 * 1000; // 5分钟毫秒数
const timeA = new Date('2024-05-20 14:30:00');
const timeB = new Date('2024-05-20 14:36:00');
console.log(isArrivalClose(timeA, timeB, threshold)); // 输出false

注意事项

  • 确保时间参数与阈值的单位一致(比如时间用秒戳,阈值就传秒数;用毫秒戳则阈值传毫秒数)。
  • 若使用时间对象,需对应语言支持的时间类型操作,避免类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:10:26