如何在React项目中使用MomentJS基于remindTime比较日期时间
解决方案
你之前的代码失效原因是直接将外层remindTime对象传入Moment构造函数,Moment无法识别该对象的时间字段,会解析为无效时间,因此比较逻辑不生效。
按以下方式修改即可实现需求:
- 第一步:提取对象内嵌套的日期、时间字段,拼接为完整的时间字符串
- 第二步:指定时间格式传入Moment构造函数,避免不同环境下的解析异常
- 第三步:推荐使用Moment内置的
isSameOrAfter方法完成比较,可读性和兼容性比直接使用运算符更好
完整代码示例
const remindTime = { _id: new ObjectId("614fa5ed18b365aa83099183"), title: 'Third Message', description: 'Item 3', remindTime: { date: '2021-09-26', time: '7:43:21 pm' }, isComplete: false, } // 拼接完整时间字符串 const targetTimeStr = `${remindTime.remindTime.date} ${remindTime.remindTime.time}` // 传入Moment并指定格式(h对应12小时制,a匹配am/pm标识) const targetMoment = moment(targetTimeStr, 'YYYY-MM-DD h:mm:ss a') // 比较当前时间是否大于等于目标时间 const isTimeReached = moment().isSameOrAfter(targetMoment)
如果你坚持要用运算符比较,可以直接对比两个Moment对象的时间戳:
const isTimeReached = moment().valueOf() >= targetMoment.valueOf()
内容的提问来源于stack exchange,提问作者Jerry Seigle
相关产品推荐
相关产品推荐

