Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

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

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';

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

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'))

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

How do I get this to work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • 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.

That's all:

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...