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

如何使用Moment.js比较日期?排查课程状态判断代码问题

课程状态判断的Moment.js代码问题排查

你用Moment.js根据课程的开始日期ngayBatDau和结束日期ngayKetThuc判断状态的代码,主要存在以下几个潜在问题:

1. 空值/无效日期未处理

当khoadaotao?.ngayBatDau或khoadaotao?.ngayKetThuc为null、undefined或格式错误时,moment()会默认创建一个当前时间的Moment对象,而非无效日期,直接调用isSameOrBefore等方法会导致逻辑完全偏离预期。

2. 当前时间精度干扰

原代码中moment()获取的是包含时分秒的完整当前时间,如果课程日期是仅日期格式(如YYYY-MM-DD),解析后会是当天0点,虽然你指定了"day"作为比较精度,但后续修改代码时容易忽略这个细节,导致比较错误。

3. 非法日期顺序未校验

如果课程的结束日期早于开始日期,原代码会直接返回Expired,但这属于非法数据,应该单独处理。


修正后的完整代码

render: (khoadaotao: khoadaotaoType): Element => {
  // 初始化日期并保留空值判断
  const ngayBatDau = khoadaotao?.ngayBatDau ? moment(khoadaotao.ngayBatDau) : null;
  const ngayKetThuc = khoadaotao?.ngayKetThuc ? moment(khoadaotao.ngayKetThuc) : null;
  // 截断当前时间到当天0点,消除时分秒干扰
  const currentDate = moment().startOf('day');

  // 处理无效日期场景
  if (!ngayBatDau?.isValid() || !ngayKetThuc?.isValid()) {
    return <Tag color="gray">无效日期</Tag>;
  }
  // 校验日期顺序合法性
  if (ngayKetThuc.isBefore(ngayBatDau, "day")) {
    return <Tag color="red">日期错误</Tag>;
  }

  // 正常状态判断逻辑
  if (ngayKetThuc.isSameOrAfter(currentDate, "day") && ngayBatDau.isSameOrBefore(currentDate, "day")) {
    return <Tag color="green">Active</Tag>;
  } else if (ngayBatDau.isAfter(currentDate, "day")) {
    return <Tag color="blue">Soon</Tag>;
  }
  return <Tag color="magenta">Expired</Tag>;
};

内容的提问来源于stack exchange,提问作者Nguyễn Tiến Đức

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:50:26