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

在JavaScript Selenium中验证相对时间序列是否升序

在JavaScript Selenium中验证相对时间的升序排列

要验证一天前、10天前这类中文相对时间的排列顺序,核心思路是把相对时间转换为可比较的时间戳,再通过时间戳的数值顺序判断原列表是否符合升序要求。以下是具体实现步骤:

1. 提取页面中的相对时间文本

先用Selenium定位所有包含相对时间的元素,提取文本内容组成数组:

// 替换为你实际使用的元素选择器(CSS/XPath均可)
const timeElements = await driver.findElements(By.css('.relative-time'));
// 批量获取元素文本
const relativeTimeList = await Promise.all(timeElements.map(el => el.getText()));

2. 编写相对时间转时间戳的函数

将中文相对时间解析为对应的时间戳(毫秒数),方便后续比较:

function convertToTimestamp(relativeTime) {
  const now = new Date();
  // 匹配数字和时间单位,兼容“一天前”“10天前”两种格式
  const matchResult = relativeTime.match(/(\d+)?(天|个月)前/);
  if (!matchResult) throw new Error(`无法解析时间字符串:${relativeTime}`);

  const count = matchResult[1] ? parseInt(matchResult[1], 10) : 1;
  const unit = matchResult[2];

  // 根据单位计算过去的时间
  if (unit === '天') {
    now.setDate(now.getDate() - count);
  } else if (unit === '个月') {
    now.setMonth(now.getMonth() - count);
  }

  // 返回时间戳(毫秒数)
  return now.getTime();
}

注:setMonth可能存在跨月边界误差(比如1月31日减1个月会变为12月31日),但这种误差不会影响时间先后的比较逻辑。

3. 验证时间戳的升序排列

将所有相对时间转换为时间戳后,检查数组是否满足升序(时间戳从小到大,对应时间从早到晚,即最远的时间在前):

function isAscendingOrder(timestamps) {
  for (let i = 0; i < timestamps.length - 1; i++) {
    // 升序要求前一个时间戳 ≤ 后一个时间戳
    if (timestamps[i] > timestamps[i + 1]) {
      return false;
    }
  }
  return true;
}

// 转换并执行验证
const timestamps = relativeTimeList.map(time => convertToTimestamp(time));
const isAscending = isAscendingOrder(timestamps);

// 测试场景可直接断言,示例如下:
// assert.strictEqual(isAscending, true, "时间未按升序排列");
console.log(`时间是否按升序排列:${isAscending}`);

如果你的“升序”指从近到远(最新时间在前,比如一天前→10天前→3个月前→6个月前),则需验证时间戳是否为降序排列,修改判断逻辑即可:

function isDescendingOrder(timestamps) {
  for (let i = 0; i < timestamps.length - 1; i++) {
    if (timestamps[i] < timestamps[i + 1]) {
      return false;
    }
  }
  return true;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 16:04:57