Skip to content
Advertisement

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:

JavaScript

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:

JavaScript

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:

JavaScript

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?

Advertisement

Answer

  • 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:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement