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

使用Moment.js对比课程结束时间与系统时间判断课程是否过期问题

解决课程过期判断的日期时间对比问题

你直接比较字符串格式的日期和时间是错误的——这种比较是按字符字典序来的,和实际的时间先后逻辑完全不匹配,这就是你得到错误结果的原因。

正确的做法是把数据库里的日期和时间拼接成完整的时间字符串,用Moment.js解析成时间对象后,再和当前时间对象做对比:

// 从数据库获取的结束日期和时间
const endDate = "03-09-22";
const endTime = "5:00 PM";

// 拼接成完整的时间字符串
const endDateTimeStr = `${endDate} ${endTime}`;
// 按指定格式解析为Moment时间对象
const endDateTime = moment(endDateTimeStr, 'DD-MM-YY hh:mm A');
// 当前系统时间的Moment对象
const currentDateTime = moment();

// 判断课程是否过期:当前时间晚于结束时间则过期
if (currentDateTime.isAfter(endDateTime)) {
  console.log('课程已过期');
} else {
  console.log('课程未过期');
}

注意事项:

  • 解析时的格式字符串'DD-MM-YY hh:mm A'必须和你的日期时间字符串格式完全对应,否则会出现解析错误
  • 永远不要直接比较日期时间字符串,Moment.js的时间对象对比是基于时间戳的,逻辑准确可靠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:54:41