1. 首页
  2. 软件开发
  3. JS实现时间段过滤搜索

JS实现时间段过滤搜索

  • 发布于 2024-09-26
  • 1 次阅读

你想要实现一个JavaScript函数,用于根据时间段过滤搜索结果吗?可以尝试以下的示例代码:

// 假设这是你的数据
const data = [
  { id: 1, name: 'Alice', timestamp: 1622382000000 }, // 2021-05-30 12:00:00 UTC
  { id: 2, name: 'Bob', timestamp: 1630335600000 }, // 2021-08-30 12:00:00 UTC
  { id: 3, name: 'Charlie', timestamp: 1640991600000 } // 2022-12-31 12:00:00 UTC
];

// 过滤函数,根据时间段搜索
function filterByTimeRange(data, startTime, endTime) {
  return data.filter(item => {
    return item.timestamp >= startTime && item.timestamp <= endTime;
  });
}

// 定义搜索时间段的开始时间和结束时间
const startTime = 1630000000000; // 2021-08-27 12:00:00 UTC
const endTime = 1640000000000; // 2022-08-27 12:00:00 UTC

// 调用过滤函数
const filteredData = filterByTimeRange(data, startTime, endTime);

// 输出过滤后的结果
console.log(filteredData);

在这个示例中,filterByTimeRange 函数接受一个数据数组、开始时间和结束时间作为参数,并返回在这个时间段内的数据项。你可以根据具体的时间戳来调整开始时间和结束时间,以适应你的需求。

原文链接: https://blog.csdn.net/hexadecimal_001/article/details/139335082