如何使用Moment判断当前时间是否落在两个给定时间区间内(仅比对时间)
问题原因
- 你调用
isBetween返回false的核心原因是Moment默认会比对完整的日期+时间信息,你示例中当前时间是6月18日,起止时间都是6月17日,完整时间维度下18日的时间必然晚于17日的结束时间,因此返回false。
解决方案
如果仅需要比对时分秒部分、忽略日期差异,只需要将三个时间的年月日统一设置为同一个任意固定值,再做区间判断即可:
import * as moment from 'moment'; const current_time = moment(current_day_time.current_time); const start = moment(batch_info.batch_start_time); const end = moment(batch_info.batch_end_time); // 统一将三个时间的日期设为同一天,这里取1970年1月1日作为统一基准日期 const fixDate = (time) => time.clone().set({year: 1970, month: 0, date: 1}); const currentTimeOnly = fixDate(current_time); const startTimeOnly = fixDate(start); const endTimeOnly = fixDate(end); let isInRange; // 兼容普通区间和跨零点区间两种场景 if (startTimeOnly.isBefore(endTimeOnly)) { isInRange = currentTimeOnly.isBetween(startTimeOnly, endTimeOnly); } else { // 区间跨零点场景,例如23:00到次日02:00的判断逻辑 isInRange = currentTimeOnly.isSameOrAfter(startTimeOnly) || currentTimeOnly.isSameOrBefore(endTimeOnly); } console.log(isInRange); // 你的示例场景下会返回true
补充说明
isBetween默认是左开右开的比对逻辑,如果需要包含起止时间,可以传第三个和第四个参数指定边界规则:isBetween(start, end, null, '[]'),其中[]代表左右边界都包含,[)代表左包含右不包含,可根据需求自行调整。
内容的提问来源于stack exchange,提问作者Mohd Sabban
相关产品推荐
相关产品推荐

