如何使用Moment.JS检查当前时间是否在2次之间 [英] How to use Moment.JS to check whether the current time is between 2 times

查看:3246
本文介绍了如何使用Moment.JS检查当前时间是否在2次之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say the current time is 09:34:00 (hh:mm:ss), and I have two other times in two variables:

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

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

How do I use Moment.JS to check whether the current time is between beforeTime and afterTime?

我见过 isBetween() ,我试过使用它像:

I've seen isBetween(), and I've tried to use it like:

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

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

but that doesn't work because as soon as I format the first (current time) moment into a string, it's no longer a moment object. I've also tried using:

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 ,因为当我格式化当前时间时,它不再是片刻。

but I get false, because again when I format the current time, it's no longer a moment.

如何让它工作?

推荐答案


  • 您可以将片刻实例传递给 isBetween()

  • 省略格式()调用,你想要的是在第二次尝试的第一时刻()传递解析格式,如int。

    • You can pass moment instances to isBetween()
    • leave out the format() calls, what you want is to pass parse formats like int the first moment() of your second attempt.
    • 这就是全部:

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

      这篇关于如何使用Moment.JS检查当前时间是否在2次之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆