如何使用Moment.JS检查当前时间是否在2次之间

How to use Moment.JS to check whether the current time is between 2 times

本文关键字:是否 时间 2次 之间 何使用 Moment JS 检查      更新时间:2023-09-26

假设当前时间是09:34:00hh:mm:ss),我在两个变量中有另外两个时间:

var beforeTime = '08:34:00',
    afterTime = '10:34:00';

如何使用Moment.JS检查当前时间是否在beforeTimeafterTime之间?

我看过isBetween(),我试着像一样使用它

moment().format('hh:mm:ss').isBetween('08:27:00', '10:27:00')

但这不起作用,因为一旦我将第一个(当前时间)时刻格式化为字符串,它就不再是一个时刻对象。我也尝试过使用:

moment('10:34:00', 'hh:mm:ss').isAfter(moment().format('hh:mm:ss')) && moment('08:34:00', 'hh:mm:ss').isBefore(moment().format('hh:mm:ss'))

但我得到了false,因为当我再次格式化当前时间时,它不再是一个瞬间。

我该如何让它发挥作用?

  • 可以将力矩实例传递给isBetween()
  • 去掉format()调用,您想要的是在第二次尝试的第一个moment()中传递解析格式,比如int

仅此而已:

const format = 'hh:mm:ss';
// var time = moment() gives you current time. no format required.
const time = moment('09:34:00', format);
const beforeTime = moment('08:34:00', format);
const afterTime = moment('10:34:00', format);
if (time.isBetween(beforeTime, afterTime)) {
  console.log('is between');
} else {
  console.log('is not between');
}
// prints 'is between'

在我的情况下,我必须使用isBetweenisSame来覆盖我在isBetween条件中使用的beforeafter时间。

function getTimeCategory(time) {
  let timeCategory = '';
  const timeFormat = 'HH:mm:ss';
  if (
    time.isBetween(moment('00:00:00', timeFormat), moment('04:59:59', timeFormat)) ||
    time.isSame(moment('00:00:00', timeFormat)) ||
    time.isSame(moment('04:59:59', timeFormat))
  ) {
    timeCategory = 'DAWN';
  } else if (
    time.isBetween(moment('05:00:00', timeFormat), moment('11:59:59', timeFormat)) ||
    time.isSame(moment('05:00:00', timeFormat)) ||
    time.isSame(moment('11:59:59', timeFormat))
  ) {
    timeCategory = 'MORNING';
  } else if (
    time.isBetween(moment('12:00:00', timeFormat), moment('16:59:59', timeFormat)) ||
    time.isSame(moment('12:00:00', timeFormat)) ||
    time.isSame(moment('16:59:59', timeFormat))
  ) {
    timeCategory = 'NOON';
  } else if (
    time.isBetween(moment('17:00:00', timeFormat), moment('23:59:59', timeFormat)) ||
    time.isSame(moment('17:00:00', timeFormat)) ||
    time.isSame(moment('23:59:59', timeFormat))
  ) {
    timeCategory = 'NIGHT';
  }
  return timeCategory;
}

我使用了矩函数组合isSameOrAfter和isSameOrBefore,而不是isBetween。

if(moment(currentTime,'HH:mm:ss').isSameOrAfter(moment(shift_dayFrom,'HH:mm:ss')) && 
moment(currentTime,'HH:mm:ss').isSameOrAfter(moment(shift_dayTo,'HH:mm:ss')))
    const beforeTime = moment(t, "HH:mm");
    const afterTime = moment(t2, "HH:mm");
    
    
             
                
   const time = moment(dueTime, "HH:mm");
    
   if(time.isSameOrAfter(beforeTime) && time.isSameOrBefore(afterTime))
                {
                  
                }

该页面上的示例是

moment('2010-10-20').isBetween('2010-10-19', '2010-10-25'); // true

在你的代码中没有对format函数的调用,所以我建议尝试

moment('09:34:00').isBetween('08:34:00', '10:34:00');